Class: Hooloo::MozartHash

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

Direct Known Subclasses

Company, Genre, Rollup, Show, Video

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(o) ⇒ MozartHash

Returns a new instance of MozartHash.



47
48
49
# File 'lib/hooloo/mozart_hash.rb', line 47

def initialize(o)
  @obj = o
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method) ⇒ Object

Honestly, we should generate methods when we initially parse the Hash instead of doing this crap in method_missing. I’ll do that later.



52
53
54
# File 'lib/hooloo/mozart_hash.rb', line 52

def method_missing(method)
  @obj[method.to_s]
end

Class Method Details

.bool(*mappings) ⇒ Object



19
20
21
22
23
# File 'lib/hooloo/mozart_hash.rb', line 19

def bool(*mappings)
  field_mapping(mappings).each do |field, mapping|
    define_method(field.to_s + '?') { @obj[mapping] }
  end
end

.cast(klass, mappings, opts = {map_array: true, map: false}) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/hooloo/mozart_hash.rb', line 34

def cast(klass, mappings, opts={map_array: true, map: false})
  field_mapping(mappings).each do |field, mapping|
    define_method(field) do
      if opts[:map] || (@obj[mapping].is_a?(Array) && opts[:map_array])
        @obj[mapping].map { |x| klass.new(x) }
      else
        klass.new @obj[mapping]
      end
    end
  end
end

.date(*mappings) ⇒ Object



14
15
16
17
18
# File 'lib/hooloo/mozart_hash.rb', line 14

def date(*mappings)
  field_mapping(mappings).each do |field, mapping|
    define_method(field) { Date.iso8601(@obj[mapping.to_s]) }
  end
end

.field_mapping(fields) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
# File 'lib/hooloo/mozart_hash.rb', line 3

def field_mapping(fields)
  fields = [fields] unless fields.is_a? Array
  fields.map do |field|
    if field.is_a?(Hash)
      arr = field.to_a[0]
      [arr[0], arr[1].to_s]
    else
      [field, field.to_s]
    end
  end
end

.float(*mappings) ⇒ Object



29
30
31
32
33
# File 'lib/hooloo/mozart_hash.rb', line 29

def float(*mappings)
  field_mapping(mappings).each do |field, mapping|
    define_method(field.to_s) { @obj[mapping.to_s].to_f }
  end
end

.uri(*mappings) ⇒ Object



24
25
26
27
28
# File 'lib/hooloo/mozart_hash.rb', line 24

def uri(*mappings)
  field_mapping(mappings).each do |field, mapping|
    define_method(field.to_s) { URI @obj[mapping.to_s] }
  end
end

Instance Method Details

#inspectObject



58
59
60
# File 'lib/hooloo/mozart_hash.rb', line 58

def inspect
  "#<%s:%014x>" % [self.class.name, object_id]
end

#respond_to?(method) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/hooloo/mozart_hash.rb', line 55

def respond_to?(method)
  @obj.has_key? method.to_s or super
end