Method: CFoundry::V1::ModelMagic#attribute

Defined in:
lib/cfoundry/v1/model_magic.rb

#attribute(name, type, opts = {}) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/cfoundry/v1/model_magic.rb', line 87

def attribute(name, type, opts = {})
  default = opts[:default]
  is_guid = opts[:guid]
  read_only = opts[:read_only]
  write_only = opts[:write_only]
  has_default = opts.key?(:default)

  read_locations[name] = Array(opts[:read] || opts[:at] || name) unless write_only
  write_locations[name] = Array(opts[:write] || opts[:at] || name) unless read_only

  read_only_attributes << name if read_only

  self.guid_name = name if is_guid

  define_method(name) do
    return @guid if @guid && is_guid

    read = read_manifest
    read.key?(name) ? read[name] : default
  end

  define_method(:"#{name}=") do |val|
    unless has_default && val == default
      CFoundry::Validator.validate_type(val, type)
    end

    @guid = val if is_guid

    @manifest ||= {}

    old = read_manifest[name]
    @changes[name] = [old, val] if old != val

    write_to = read_only ? self.class.read_locations : self.class.write_locations

    put(val, @manifest, write_to[name])
  end

  private name if write_only
  private :"#{name}=" if read_only
end