Save configuration in Rails file

I want to accomplish the same thing that Rails did to store configurations in rb files that are read by the application:

# routes.rb
MyApp::Application.routes.draw do |map|
  root :to => 'firstpage#index'
  resources :posts

On rails, the root and resources methods are not defined in the "main" area of ​​the object.

This means that these methods are defined either by a module or by a class. But how did they require the route.rb file and used these methods from the class / module.

Because if I use "require", then these methods will be executed in the "main" area, regardless of where I run "require".

So, how would you like Rails to read this configuration file and run the methods defined in the class / module?

thank

+3
3

, yield Proc#call draw. , instance_eval class_eval.

() , draw:

def draw(&blk)
  class << context = Object.new
    def root(p1, p2)
      # ...
    end
    def resources(p1, p2)
      # ...
    end
  end
  context.instance_eval(&blk)
end

:

draw do
  root 2, 3
  resources 4, 5
end
+1

. require , . . eval Ruby, . , .

+3

, , :

class A
  eval(File.read('yourfile.rb'))
end
+2

Source: https://habr.com/ru/post/1757252/


All Articles