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


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

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


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

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


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

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


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

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
      merge_hash = {}
      setting_name.each_key { |k| merge_hash[k] = send("#{k}_context").to_hash }

      @settings.to_hash.merge(
        merge_hash
      )
    end
  end
end

.simple_settings_methods(setting_name, new_config_class) ⇒ Object


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

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