Srikan
Srikan

Reputation: 2241

Setting and accessing variables in Ruby

module YourApp
   class Application < Rails::Application
      config.my_custom_variable = :custom_value
   end
end

This works in my Rails application. I just want to understand how this works from ruby perspective. As per to my minimal ruby knowledge, there must be getter and setter(my_custom_variable=) for my_custom_variable in the config(Rails::Application::Configuration) object. Since this is my custom variable this will not be present in the Configuration object instance. How is it dynamically created/added. ?

Can somebody please explain?, direct me to the proper documentation to understand this.

Upvotes: 0

Views: 64

Answers (2)

Steve Wilhelm
Steve Wilhelm

Reputation: 6260

Not how Rails implements it, but achieve similar functionality in Ruby

require 'ostruct'

module YourApp
    class Application
        @@config = OpenStruct.new

        def self.config
           return @@config
        end
    end
end

YourApp::Application.config.my_custom_variable = :custom_value
puts YourApp::Application.config.my_custom_variable
>> custom_value

Upvotes: 0

micahbf
micahbf

Reputation: 627

Rails is using method_missing here to catch any method called on config. Then, it just adds it into a hash of options.

You can see the relevant source code here.

Upvotes: 2

Related Questions