Module: Grape::Util::StrictHashConfiguration

Extended by:
ActiveSupport::Concern
Defined in:
lib/grape/util/strict_hash_configuration.rb

Defined Under Namespace

Modules: DSL Classes: SettingsContainer

Class Method Summary collapse

Class Method Details

.config_class(*args) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/grape/util/strict_hash_configuration.rb', line 33

def self.config_class(*args)
  new_config_class = Class.new(SettingsContainer)

  args.each do |setting_name|
    if setting_name.respond_to? :values
      nested_settings_methods(setting_name, new_config_class)
    else
      simple_settings_methods(setting_name, new_config_class)
    end
  end

  new_config_class
end

.create_class_mod(args) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/grape/util/strict_hash_configuration.rb', line 91

def self.create_class_mod(args)
  new_module = Module.new do
    def config_context
      @config_context ||= config_class.new
    end
  end

  new_module.tap do |class_mod|
    new_config_class = config_class(*args)

    class_mod.send(:define_method, :config_class) do
      @config_class ||= new_config_class
    end
  end
end

.module(*args) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/grape/util/strict_hash_configuration.rb', line 78

def self.module(*args)
  new_module = Module.new do
    extend ActiveSupport::Concern
    include DSL
  end

  new_module.tap do |mod|
    class_mod = create_class_mod(args)

    mod.const_set(:ClassMethods, class_mod)
  end
end

.nested_settings_methods(setting_name, new_config_class) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/grape/util/strict_hash_configuration.rb', line 56

def self.nested_settings_methods(setting_name, new_config_class)
  new_config_class.class_eval do
    setting_name.each_pair do |key, value|
      define_method :"#{key}_context" do
        @contexts[key] ||= Grape::Util::StrictHashConfiguration.config_class(*value).new
      end

      define_method key do |&block|
        send(:"#{key}_context").instance_exec(&block)
      end
    end

    define_method :to_hash do
      @settings.to_hash.merge(
        setting_name.each_key.with_object({}) do |k, merge_hash|
          merge_hash[k] = send(:"#{k}_context").to_hash
        end
      )
    end
  end
end

.simple_settings_methods(setting_name, new_config_class) ⇒ Object



47
48
49
50
51
52
53
54
# File 'lib/grape/util/strict_hash_configuration.rb', line 47

def self.simple_settings_methods(setting_name, new_config_class)
  setting_name_sym = setting_name.to_sym
  new_config_class.class_eval do
    define_method setting_name do |new_value|
      @settings[setting_name_sym] = new_value
    end
  end
end