Ruby : Passing data to including module

Sometimes but not often in programming career in Ruby, you need to pass some sort of data to the module that is being included into your class. Firstly, I wondered how would I do that. Luckly Ruby is the only language ( I think) where you can do anything to solve problems.

The only limitation is your imagination and the Language never stops you doing anything. Since you can modify anything,  you end up with your own version of Ruby which you have created using Metaprogramming.

Solution

module GarageOwners
  module UniqueKeyValidatable
    extend ActiveSupport::Concern

    included do
      prepend_before_filter :set_current_user_from_code!,
                            only: @@actions , if: -> { params[:unique_key] }
      skip_before_action    :authenticate_garage_owner!,
                            only: @@actions, if: -> { params[:unique_key] }
    end

    def self.[](actions)
      @@actions = actions
      self
    end
end

module GarageOwners
  class MyController
    include UniqueKeyValidatable[:show]
  end
end

Explanation

I created a class method [] in the module and passed the data via that method. Stored that data in @@class_variable to be used inside the module.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s