ruby-on-railsrubyrubygemsinitializerrailtie

Best way to write initializers on a gem


I'm writing my first gem, and I've some issues with initializers part.

So I read about Railtie, and I'm little bit confused, there is part that talks about initializers and something on generators.

According to this thread, he suggested using generator Rails how to create an initializer inside a gem

So I'm not sure what's the best way.

Anyway I tried to do some initializer that add some method to Jbuilder

module MyGem
  class Railtie < Rails::Railtie
    initializer "my_gem.jbuilder_custom_cache" do |variable|
      class JbuilderTemplate
        def custom_cache!(resource, name, &block)
          fragment_cache_key = ::MyGem::Logic.cache_key(name, resource)
          options = { expires_in: 1.hour }
          cache!(fragment_cache_key, options, &block)
        end
      end
    end
  end
end

This didn't work well.


Solution

  • This is untested, but I think you can do:

    module MyGem
      class Railtie < Rails::Railtie
        config.to_prepare do
          JbuilderTemplate.class_eval do 
            def custom_cache!(resource, name, &block)
              fragment_cache_key = ::MyGem::Logic.cache_key(name, resource)
              options = { expires_in: 1.hour }
              cache!(fragment_cache_key, options, &block)
            end
          end
        end
      end
    end
    

    See here (http://api.rubyonrails.org/classes/Rails/Railtie.html#class-Rails::Railtie-label-Configuration) for more information about the config.to_prepare block.