Class: KungFigure::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/kung_figure.rb

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(key, &block) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/kung_figure.rb', line 98

def method_missing(key,&block)
  @props ||= {}
  klazz_name = camelize(key.to_s).to_sym
  child_cfg_clazz = self.class.const_get(klazz_name) if self.class.const_defined?(klazz_name)
  child_cfg_clazz ||= get_from_enclosing_module(klazz_name)

  raise "No such configuration #{key}" unless child_cfg_clazz

  unless @props.key?(key)
    @props[key] = if child_cfg_clazz.ancestors.include?(KungFigure::Base)
                    child_cfg_clazz.new
                  elsif child_cfg_clazz.respond_to?(:config)
                    child_cfg_clazz.config
                  end
  end
  @props[key].instance_eval(&block) if block_given?
  return @props[key]
end

Class Method Details

.define_prop(name, default) ⇒ Object



73
74
75
76
77
78
79
80
81
82
# File 'lib/kung_figure.rb', line 73

def define_prop(name,default)
  define_method(name) do |*args|
    @props ||= {}
    if args.length > 0
      @props[name] = args[0]
    else
      @props.key?(name) ? @props[name] : default
    end
  end
end

Instance Method Details

#camelize(str) ⇒ Object



85
86
87
# File 'lib/kung_figure.rb', line 85

def camelize(str)
  str.split('_').map{|l| l.capitalize}.join('')
end

#get_from_enclosing_module(klazz_name) ⇒ Object



89
90
91
92
93
94
95
96
# File 'lib/kung_figure.rb', line 89

def get_from_enclosing_module(klazz_name)
  config_klazz_path=self.class.name.to_s.split('::')[0..-2]
  config_klazz_path<< klazz_name
  config_klazz_path.inject(Object){|parent,nxt|
    break unless parent.const_defined?(nxt.to_sym)
    parent.const_get(nxt.to_sym)
  }
end