class Plyushkin::BaseValue
Public Class Methods
formatters()
click to toggle source
# File lib/plyushkin/base_value.rb, line 56 def self.formatters if self.superclass == Object @formatters ||= {} else @formatters ||= superclass.formatters.dup end end
new(attr={})
click to toggle source
# File lib/plyushkin/base_value.rb, line 4 def initialize(attr={}) @new_record = attr[:new_record].nil? ? true : attr[:new_record] attr = attr.dup @date = attr.delete(:date) || DateTime.current attr.each do |k,v| send("#{k}=", v) if respond_to?("#{k}=") end end
persisted_attr(*attributes)
click to toggle source
# File lib/plyushkin/base_value.rb, line 26 def self.persisted_attr(*attributes) opts = attributes.last.is_a?(Hash) ? attributes.pop : {} names = attributes formatter = opts[:formatter] names.each{|name| formatters[name] = formatter} persisted_attributes.concat(names) attr_writer *names names.each do |name| define_method(name) do value = instance_variable_get("@#{name}") if formatter send(formatter, value) else value end end end end
persisted_attributes()
click to toggle source
# File lib/plyushkin/base_value.rb, line 48 def self.persisted_attributes if self.superclass == Object && self.superclass.class == Class @persisted_attributes ||= [] else @persisted_attributes ||= superclass.persisted_attributes.dup end end
Public Instance Methods
equal_value?(other)
click to toggle source
# File lib/plyushkin/base_value.rb, line 69 def equal_value?(other) self.class.persisted_attributes.each do |attribute| return false if attribute != :date && send(attribute) != other.send(attribute) end true end
formatters()
click to toggle source
# File lib/plyushkin/base_value.rb, line 22 def formatters @formatters.dup end
mark_persisted()
click to toggle source
# File lib/plyushkin/base_value.rb, line 18 def mark_persisted @new_record = false end
new_record?()
click to toggle source
# File lib/plyushkin/base_value.rb, line 14 def new_record? @new_record end
to_bool(value)
click to toggle source
# File lib/plyushkin/base_value.rb, line 95 def to_bool(value) return true if [1, "1", "true"].include?(value) return false if [0, "0", "false"].include?(value) return value end
to_date(value)
click to toggle source
# File lib/plyushkin/base_value.rb, line 91 def to_date(value) value.is_a?(String) ? DateTime.parse(value) : value end
to_f(value)
click to toggle source
TODO: Maybe this can be nicer.
# File lib/plyushkin/base_value.rb, line 81 def to_f(value) begin Float(value) rescue ArgumentError => e value rescue TypeError => e value end end
to_i(value)
click to toggle source
# File lib/plyushkin/base_value.rb, line 76 def to_i(value) value =~ /\A\d+(\.\d+)?\Z/ ? value.to_i : value end