Class: JSONdb::Record
- Inherits:
-
Object
- Object
- JSONdb::Record
- Includes:
- Logger, Validations::Types
- Defined in:
- lib/jsondb/record.rb
Constant Summary
Constants included from Validations::Types
Validations::Types::AllowedTypes
Instance Attribute Summary collapse
-
#table_name ⇒ Object
readonly
Returns the value of attribute table_name.
Instance Method Summary collapse
- #data_from_hash(hash) ⇒ Object
- #fields ⇒ Object
-
#initialize(table_name, record = nil) ⇒ Record
constructor
A new instance of Record.
-
#method_missing(name, *args) ⇒ Object
def updated_at Time.at(@updated_at) end.
- #set_default_if_nil(name) ⇒ Object
- #to_hash ⇒ Object
Methods included from Logger
#allowed_log_level?, #log, #log_enabled?, #log_this?
Methods included from Validations::Types
#allowed_type?, #validate_type
Constructor Details
#initialize(table_name, record = nil) ⇒ Record
Returns a new instance of Record.
10 11 12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/jsondb/record.rb', line 10 def initialize(table_name, record = nil) @record = Hash.new @table_name = table_name if record.nil? @new_record = true @persisted = false else @new_record = false @persisted = true @record = record end end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args) ⇒ Object
def updated_at
Time.at(@updated_at)
end
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/jsondb/record.rb', line 54 def method_missing(name, *args) name = name.to_s if JSONdb.fields[table_name].to_hash.keys.include?(name.sub('=', '')) if name =~ /=$/ if @record[name] != args[0] @record[name.sub('=', '')] = args[0] end else set_default_if_nil(name) # returns default value if value(name) is nil end else log("Column '#{name.sub('=', '')}' do not exists", :error) end end |
Instance Attribute Details
#table_name ⇒ Object (readonly)
Returns the value of attribute table_name.
8 9 10 |
# File 'lib/jsondb/record.rb', line 8 def table_name @table_name end |
Instance Method Details
#data_from_hash(hash) ⇒ Object
39 40 41 42 43 |
# File 'lib/jsondb/record.rb', line 39 def data_from_hash(hash) hash.each do |key, value| @record[key] = value end end |
#fields ⇒ Object
24 25 26 |
# File 'lib/jsondb/record.rb', line 24 def fields JSONdb.fields[table_name].to_hash.keys end |
#set_default_if_nil(name) ⇒ Object
32 33 34 35 36 37 |
# File 'lib/jsondb/record.rb', line 32 def set_default_if_nil(name) if @record[name].nil? @record[name] = JSONdb.fields[table_name][name].default if JSONdb.fields[table_name][name].default.nil? == false end return @record[name] end |
#to_hash ⇒ Object
28 29 30 |
# File 'lib/jsondb/record.rb', line 28 def to_hash @record end |