Class: Hash

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from_attr(obj, key_strategy = :underscore) ⇒ Object

Creates Hash object which contains the readable instance variables of ‘obj’. It’s possible to customize the key convention by ‘key_strategy’.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/hash_ninja/core_ext.rb', line 26

def self.from_attr(obj, key_strategy = :underscore)
  hash = {}
  obj.instance_variables.each do |attr|
    original_key = attr.to_s.delete('@')
    case key_strategy
      when :underscore
        key = original_key.underscore
      when :camelize
        key = original_key.camelize
      when :camelize_lower
        key = original_key.camelize(:lower)
      when :classify
        key = original_key.classify
      else
        key = original_key
    end
    begin
      hash[key.to_sym] = obj.send(original_key.to_sym)
    rescue NoMethodError => e
    end
  end
  hash
end

Instance Method Details

#activate!Object

Updates itself as HashNinja::ActiveHash destructively. ‘active_support’ will be also applied.



14
15
16
17
# File 'lib/hash_ninja/core_ext.rb', line 14

def activate!
  self.extend HashNinja::ActiveHash
  self
end

#to_attr_readerObject

Provides HashNinja::HashAccessor object



20
21
22
# File 'lib/hash_ninja/core_ext.rb', line 20

def to_attr_reader
  HashNinja::HashAttrReader.new(self)
end