Class: TryApi::Base

Inherits:
Object
  • Object
show all
Defined in:
app/models/try_api/base.rb

Direct Known Subclasses

ExampleResponse, Header, MenuItem, Method, Parameter, Project

Constant Summary collapse

@@instance_count =
0

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.typesafe_accessor(name, type, options = {}) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'app/models/try_api/base.rb', line 7

def self.typesafe_accessor(name, type, options={})

  define_method(name) do
    instance_variable_get("@#{name}")
  end

  define_method("#{name}=") do |value|
    if value.is_a?(type) || value.nil?
      value = options[:default] if value.nil? && !options[:default].nil?
      instance_variable_set("@#{name}", value)
    else
      raise TryApi::ArgumentError.new
    end
  end
end

Instance Method Details

#idObject



45
46
47
# File 'app/models/try_api/base.rb', line 45

def id
  @id ||= @@instance_count += 1
end

#to_jsonObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'app/models/try_api/base.rb', line 23

def to_json
  result = {}

  self.instance_variables.each do |i|
    value = self.instance_variable_get(i)
    if value.instance_of?(Array)
      result[i.to_s.gsub('@', '')] = value.map(&:to_json)
    else
      if i == :@project

      else
        result[i.to_s.gsub('@', '')] = value
      end
    end
  end

  result.merge!({id: self.id})
  result.with_indifferent_access
end