Code Monkey home page Code Monkey logo

render_anywhere's Introduction

DEPRECATED: This gem is no longer needed as of Rails 5. Use ActionController::Renderer instead.

render_anywhere

Out of the box, Rails can render templates in a controller context only. This little gem allows for calling "render" from anywhere: models, background jobs, rake tasks, you name it.

Installation

    gem install render_anywhere

Usage

Put render_anywhere in your Gemfile:

    gem 'render_anywhere', :require => false

In your Rails app, in a rake task, model, background job, or where ever you like, require render_anywhere, include the module and call render with the same arguments as ActionController::Base#render takes. It will return a string.

    require 'render_anywhere'

    class AnyClass
      include RenderAnywhere

      def build_html
        html = render :template => 'normal/template/reference',
                      :layout => 'application'
        html
      end
      # Include an additional helper
      # If being used in a rake task, you may need to require the file(s)
      # Ex: require Rails.root.join('app', 'helpers', 'blog_pages_helper')
      def include_helper(helper_name)
        set_render_anywhere_helpers(helper_name)
      end

      # Apply an instance variable to the controller
      # If you need to use instance variables instead of locals, just call this method as many times as you need.
      def set_instance_variable(var, value)
        set_instance_variable(var, value)
      end

      class RenderingController < RenderAnywhere::RenderingController
        # include custom modules here, define accessors, etc. For example:
        attr_accessor :current_user
        helper_method :current_user
      end

      # If you define custom RenderingController, don't forget to override this method
      def rendering_controller
        @rendering_controller ||= self.class.const_get("RenderingController").new
      end
    end

Thanks

Yapp, whose CTO (me) kindly agreed to open source this library. App yourself!

The basic approach used here came from this gist by Julien Guimont aka juggy. Thanks!

Contributing

Run tests with rake or rspec.

Run tests against different versions of rails with appraisal rake or appraisal rspec.

Author

Luke Melia, @lukemelia, lukemelia.com

License

The MIT License. Copyright (c) 2011, Yapp, Inc.

render_anywhere's People

Contributors

ankane avatar lluis avatar lukemelia avatar manuelmeurer avatar robb1e avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

render_anywhere's Issues

Public files can't be linked to

Using an image tag with paperclip. In a regular view, the server will look in 'public' automatically for any files referenced. When I try to render this in a model I can't link to the file.

can't use fragment caching with render_anywhere

Hi there,

When I try to use fragment caching with render_anywhere, I get this error:

Rendered reviews/print.html.haml within layouts/print (592.2ms)
ActionView::Template::Error: undefined method `perform_caching' for #<RenderAnywhere::RenderingController:0x007fb5e9c7dcc8>
from /Users/steven/.rvm/gems/ruby-1.9.2-p320/gems/actionpack-3.2.11/lib/action_view/helpers/cache_helper.rb:35:in `cache'

In production.rb and development.rb I have:

config.action_controller.perform_caching = true

Four years and version 0.0.11?

Time for a 1.0 release? Or if there any doubts at least 0.9?

A CHANGELOG.md file to celebrate would be appreciated too :)

Assets issue when rendering from background job

Hey guys,

We're having some issues not specifically related to render_anywhere but you may be able to shed some light on them.

In our rails 3.2 app, we're using a Sidekiq job for refreshing cache on the background, below is the snippet for the base class and one of the workers:

require 'render_anywhere'

module CacheRenderer
  class Base
    include Sidekiq::Worker
    include RenderAnywhere
  end
end

# ------------------------------------

module CacheRenderer
  class RecentEventRsvps < Base
    #do not enqueue a rendering job more than once for the same petition over a 2 minute period
    sidekiq_options unique: true, unique_job_expiration: 2 * 60

    def perform(event_id)
      event = Event.find(event_id)
      content_to_cache = render(partial: 'shared/attendees_carousel', locals: { ... })
      Rails.cache.write(['recent_event_rsvps', event.cache_key], content_to_cache)
    end
  end
end

Now this is rendered just fine in development, where assets are not precompiled, but in other environments a AssetNotPrecompiledError exception is risen for an image referenced from an image_tag. Doing some debugging we found that Rails.application.config.assets.digests is nil when the job is ran. Assets are synced to S3 using asset_sync.
Have you ever seen this kind of issues? Do you know if we need to perform any manual initialization for sprockets on the sidekiq job?

Thanks in advance,
Diego.

Rails 3.2 support?

I can't get properly digested assets using this class. The image_tag helper for instance doesn't return properly digested assets through sprockets. I tried adding the following to the Renderer controller:

  include ActionView::Helpers
  include Sprockets::Helpers::RailsHelper

  def config
    Rails.configuration.action_controller
  end

Which we use elsewhere for generating asset paths, but when I do it in here I get the following stack trace:

RuntimeError: ActionView::Helpers::ControllerHelper#controller_path delegated to controller.controller_path, but controller is nil: #<Infl::TestRenderer:0x007fbc2e1c38a0 @_routes=nil, @_action_has_layout=true>
  from /Users/influitivedev/.rvm/gems/ruby-2.0.0-p353@influitive/gems/actionpack-3.2.13/lib/action_view/helpers/controller_helper.rb:13:in `rescue in controller_path'
  from /Users/influitivedev/.rvm/gems/ruby-2.0.0-p353@influitive/gems/actionpack-3.2.13/lib/action_view/helpers/controller_helper.rb:10:in `controller_path'
  from /Users/influitivedev/.rvm/gems/ruby-2.0.0-p353@influitive/gems/actionpack-3.2.13/lib/abstract_controller/view_paths.rb:36:in `_prefixes'
  from /Users/influitivedev/.rvm/gems/ruby-2.0.0-p353@influitive/gems/actionpack-3.2.13/lib/abstract_controller/view_paths.rb:45:in `lookup_context'
  from /Users/influitivedev/.rvm/gems/ruby-2.0.0-p353@influitive/gems/actionpack-3.2.13/lib/abstract_controller/rendering.rb:81:in `view_renderer'
  from /Users/influitivedev/.rvm/gems/ruby-2.0.0-p353@influitive/gems/actionpack-3.2.13/lib/action_view/helpers/rendering_helper.rb:24:in `render'
  from (irb):36
  from /Users/influitivedev/.rvm/gems/ruby-2.0.0-p353@influitive/gems/railties-3.2.13/lib/rails/commands/console.rb:47:in `start'
  from /Users/influitivedev/.rvm/gems/ruby-2.0.0-p353@influitive/gems/railties-3.2.13/lib/rails/commands/console.rb:8:in `start'
  from /Users/influitivedev/.rvm/gems/ruby-2.0.0-p353@influitive/gems/railties-3.2.13/lib/rails/commands.rb:41:in `<top (required)>'
  from script/rails:6:in `require'
  from script/rails:6:in `<main>'

Any ideas?

Fragment caching with cache_digests

Receiving the following error only when using caching.

ActionView::Template::Error: undefined local variable or method `view_cache_dependencies' for #<#<Class:0x007fa2e4a3c008>:0x007fa2e9fd4510>
    from /Users/jarrettgreen/.rvm/gems/ruby-1.9.3-p429@balancedcomp/gems/cache_digests-0.3.1/lib/cache_digests/fragment_helper.rb:22:in `fragment_for'
    from /Users/jarrettgreen/.rvm/gems/ruby-1.9.3-p429@balancedcomp/gems/actionpack-3.2.17/lib/action_view/helpers/cache_helper.rb:36:in `cache'
    from /Users/jarrettgreen/code/balanced-comp/app/views/scenario_entries/_scenario_entry.html.haml:1:in `_app_views_scenario_entries__scenario_entry_html_haml__1591820996871809986_70168843571460'

Using the following method in a model:

  def build_html
    render :partial => 'scenario_entries/scenario_entry',
           :locals => {:scenario_entry => self, :@scenario => self.scenario},
           :formats => :html
  end

Partial looks like this:

-cache scenario_entry do 
  %tr.strong
    %td=scenario_entry.employee.full_name_reversed
    %td=scenario_entry.employee.position.title
    %td{:colspan => 2}

    #etc

Using
render_anywhere (0.0.8)
cache_digests (0.3.1)
Rails 3.2.17

Rendering a partial

Hi there,

thanks for your work!

I'd like it to be possible to render a partial easily through just render my_object - which then calls to_partial_path sets the right locals and renders it.

When I try it, I get an error because it tries to name space it as render_anywhere which of course does not work, e.g.:

ActionView::MissingTemplate: Missing partial render_anywhere/cover_pages/_cover_page with {:locale=>[:en], :formats=>[:html, :text, :js, :css, :ics, :csv, :vcf, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :haml, :jbuilder]}. Searched in:

Maybe it's already possible and I'm just missing something.

Thank you!
Tobi

Add LICENSE file and also add to gem spec

Although the licensing is mentioned in the README, it would be best to include the actual file as normal, and also to update the gem spec so one can trivially list licensing information from all gems in a project, and it just works.

Error when rendering inside a model class method

I've got a Message model with a method for creating standard system information messages.

def self.create_system_message(user, message)
  self.create(user_id:user.id, head:"System message!", text: render(partial: message))
end

But this method raises an error saying

undefined method `render' for #<Class:0x00000009abba18>

What's the problem and how do I get rid of it?

Can't find my template

Hi there,

I have:

/app/views/reviews/print.html.haml

In my review.rb model, I have:

html = render "reviews/print", :locals => {etc etc}

Why am I getting this error?:

ActionView::MissingTemplate: Missing template render_anywhere/rendering/print with {:locale=>[:en], :formats=>[:html, :text, :js, :css, :ics, :csv, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip], :handlers=>[:erb, :builder, :coffee, :haml]}. Searched in:
  * "/Users/steven/Dropbox/Testivate/app/views"
from /Users/steven/.rvm/gems/ruby-1.9.2-p320/gems/pry-exception_explorer-0.1.9/lib/pry-exception_explorer/core_ext.rb:46:in `raise'

ActionView::Template::Error: Missing host to link to!

I'm using Rails 4.1, and getting:

ActionView::Template::Error:
       Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true

...when running on a template that contains asset paths. I was able to solve this by updating production.rb, development.rb etc to set Rails.application.routes.default_url_options:

Rails.application.routes.default_url_options = config.action_mailer.default_url_options = { :host => 'examplecom', :protocol => 'https' }

This seems to work, but since I can imagine this is a common issue, wondering if there's a better way?

`params` not defined

Hey Luke,

I'm using Rails 4 and am trying to add render_anywhere, I'm using the fork from @magnusvk for the lazy loading of route helpers and I've also had issues with params being undefined. I opened the controller in my app to get this to work but would be good to get into the library.

class RenderAnywhere::RenderingController
  def params
    {}
  end
end

Instace variables in templates

well, while in controller, maybe is

class TestController < ActionCtonroller::Base
def index
  @books = Book.all
end
end

and then,

require 'render_anywhere'
class TestStatic
  def intialize(book)
    @book = book
  end

  def body
    html = render(template: "book/index.html.erb", layout: "application")
    p html
  edn
end

When run, it raise an error sth about @each is a nil class

Webpacker: support javascript_packs_with_chunks_tag

Webpacker in rails 5.2 adds javascript_packs_with_chunks_tag, which calls send_early_hints, which isn't implemented here.

Workaround:

  class RenderingController < RenderAnywhere::RenderingController
    def request
      r = super
      def r.send_early_hints(links)
      end
      r
    end
  end

Rails 4.1 uninitialized constant AbstractController::Layouts

Hello,
getting:

/Users/kain/.rvm/gems/ruby-2.1.0/gems/render_anywhere-0.0.4/lib/render_anywhere/rendering_controller.rb:6:in `<class:RenderingController>': uninitialized constant AbstractController::Layouts (NameError)
    from /Users/kain/.rvm/gems/ruby-2.1.0/gems/render_anywhere-0.0.4/lib/render_anywhere/rendering_controller.rb:2:in `<module:RenderAnywhere>'
    from /Users/kain/.rvm/gems/ruby-2.1.0/gems/render_anywhere-0.0.4/lib/render_anywhere/rendering_controller.rb:1:in `<top (required)>'

with Rails 4.1.x

Unset an instance variable?

We are using render_anywhere to render a series of pages, and as such there is a loop.

There are some instances where instance variables are set on iterations of the loop that won't be needed on the next iteration. Leaving them assigned causes rendering issues, but there is no unset_instance_variable method (or similar).

Re-initializing the object which uses the render_anywhere gem on each iteration of the loop would evidently solve this but would be an expensive operation.

Would adding a method like the following be a viable solution?

def unset_instance_variable(var) 
  rendering_controller.class_eval do
    undef :"#{var}"
    undef :"#{var}="
  end
end

rails4 form rendered via render_anywhere does not contain authenticity_token

I am new to this so forgive if I am issing something obvious. I have a partial that renders a simple form. If I render this partial from a view, it works fine. If I render the same partial via render_anywhere the resulting form does not have an authenticity token and therefore any attempts to submit the form will fail. Also the methods to add the authenticity token <%= token_tag form_authenticity_token %> do not work because form_authenticity_token is reported as undefined.

Looking at the code, I can see that protect_against_forgery? is basically nilled out, with a comment saying 'we are not in a browser, no need for this'. In my case the rendered html does ultimately end up in a browser so I do need this. I've also just noticed that the controller path helper (e.g. form_tag mycontroller_path) doesn't work either.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.