Module: SimplifyApi

Defined in:
lib/simplify_api/version.rb,
lib/simplify_api/simplify_api.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

VERSION =
"0.1.1"

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object



66
67
68
69
70
71
72
73
# File 'lib/simplify_api/simplify_api.rb', line 66

def method_missing(method_name, *args, &block)
  case method_name
  when /(.*)\=$/
    create_and_set_instance_variable("#{$1}", args[0])
  else
    super(method_name, args, block)
  end
end

Class Method Details

.included(base) ⇒ Object



2
3
4
5
6
7
8
9
10
# File 'lib/simplify_api/simplify_api.rb', line 2

def self.included(base)
  base.singleton_class.send(:attr_accessor, :attributes)
  base.attributes = {}
  base.singleton_class.send(:attr_accessor, :mandatory)
  base.mandatory = []
  base.singleton_class.send(:attr_accessor, :default)
  base.default = {}
  base.extend(ClassMethods)
end

Instance Method Details

#initialize(opts) ⇒ Object

Raises:

  • (ArgumentError)


30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/simplify_api/simplify_api.rb', line 30

def initialize(opts)
  opts.each_pair do |k, v|
    case v
    when Hash
      v = self.class.attributes[k.to_sym][:type].new(v)
    when Array
      v.collect! { |i| self.class.attributes[k.to_sym][:params][:array_type].new(i) }
    end
    create_and_set_instance_variable("#{k}", v)
  end
  raise ArgumentError, "Missing mandatory attributes => #{self.class.mandatory-self.instance_variables}" if not mandatory_attributes_in?
  self.class.default.each_pair do |k, v|
    create_and_set_instance_variable(k, v) unless self.instance_variables.include?("@#{k}".to_sym)
  end
  self
end

#respond_to_missing?(method_name, *args) ⇒ Boolean



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

def respond_to_missing?(method_name, *args)
  case method_name
  when /(.*)\=$/
    true # always respond to assignment methods
  else
    super(method_name, args)
  end
end

#to_hObject



47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/simplify_api/simplify_api.rb', line 47

def to_h
  h = {}
  instance_variables.each do |i|
    k = /\@(.*)/.match(i.to_s)[1].to_sym
    v = instance_variable_get(i)
    if v.class == Array then
      h[k] = []
      v.each {|a| h[k] << (a.respond_to?(:to_h) ? a.to_h : a) }
    else
      h[k] = v.respond_to?(:to_h) ? v.to_h : v
    end
  end
  return h
end

#to_jsonObject



62
63
64
# File 'lib/simplify_api/simplify_api.rb', line 62

def to_json
  self.to_h.to_json
end