2

I'm building a gem in Rails which is a simple admin interface. I have experience with building rails applications but this is the first time I'm developing a gem and i have a problem with the concept of making methods in my gem part of the rails internals.

For example i want my three methods which are part of my gem to be accessible through rails application. The methods are: my_controller_method, my_model_method, my_view_method

# lib/my_gem/view_helpers.rb
module MyGem
  module ViewHelpers
    def my_view_method(data)
      # super mega stuff
    end
  end
end

# lib/my_gem/active_record.rb
module MyGem
  module ActiveRecord
    def my_model_method(data)
      # super mega stuff
    end
  end
end

# lib/my_gem/controller_additions.rb
module MyGem
  module ControllerAdditions
    def my_controller_method(data)
    # super mega stuff
    end
  end
end

So i want these methods be available in my rails MVC architecture. For example

#app/models/institution.rb
class Institution < ActiveRecord::Base
  validates_presence_of :contact_person, :phone_number, :email
  my_model_method :some_data
end

#app/controllers/institutions_controller.rb
class InstitutionsController < ApplicationController
  my_controller_method :some_data
end

#app/views/institutions/index.html
<h1></h1>
<%= my_view_method(some_data) %>

So what is the best way to add methods from my gem to rails MVC?

1 Answer 1

1

In lib/my_gem.rb you can use the poorly documented ActiveSupport#on_load, e.g.

require 'my_gem/view_helpers'
require 'my_gem/active_record'
require 'my_gem/controller_additions'

ActiveSupport.on_load(:action_view) do
  include MyGem::ViewHelpers
end

ActiveSupport.on_load(:active_record) do
  extend MyGem::ActiveRecord
end

ActiveSupport.on_load(:action_controller) do
  extend MyGem::ControllerAdditions
end

In this blog post, Yehuda Katz talks a bit more about the surroundings. This might be an interesting read for you as well!

Sign up to request clarification or add additional context in comments.

2 Comments

Added link to related blog post.
There was a small problem, needed to change include/extend. ViewHelper module was included, ActiveRecord and ControllerAdditions modules where extended. And then it worked :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.