Commit 0b4ba35b by Ivan Lan

Merge branch 'lan/add_input_proc_to_Ohm' into 'master'

Add input_proc to Ohm method my_attribute See merge request !14
parents 90983ca7 6cb4249a
module WeatherModel
module SourceSchema
end
end
\ No newline at end of file
......@@ -2,7 +2,8 @@ module WeatherModel
module Storer
require 'active_record'
require 'ohm'
require "ohm/expire"
require 'ohm/expire'
require 'rails'
class Mysql < ::ActiveRecord::Base
after_save :update_ohm
......@@ -64,9 +65,9 @@ module WeatherModel
index :mysql_id
unique :mysql_id
settings[:schema].each_pair { |attr, type|
attribute attr, type_proc(type)
}
settings[:schema].each_pair do |attr, type|
my_attribute attr, type
end
set_options settings
end
......@@ -83,6 +84,13 @@ module WeatherModel
super.select{ |x| x.attributes.empty?}.map(&:delete)
super
end
# if method_defined? :datatime=
# def datatime= val
# val = val.strftime("%Y-%m-%d %H:%M:%S") if val.is_a?(Time)
# super val
# end
# end
# # Write the dictionary of key-value pairs to the model.
def method_missing(method, *args)
......@@ -93,20 +101,43 @@ module WeatherModel
end
end
def self.type_proc type
def self.my_attribute name, type
attributes << name unless attributes.include?(name)
output_proc = output_proc_sellector(type)
input_proc = input_proc_sellector(type)
define_method(name) do
output_proc[@attributes[name]]
end
define_method(:"#{name}=") do |value|
@attributes[name] = input_proc[value]
end
end
def self.output_proc_sellector type
case type
when :integer
proc { |val| val && val.to_i }
when :float
proc { |val| val && val.to_f }
when :datetime
proc { |val| val.is_a?(String) ? Time.parse(val) : val}
when :json
proc { |value|
value.is_a?(String) ?
JSON.parse(value.gsub('=>', ':')) :
value
}
else
proc { |val| val }
end
end
def self.input_proc_sellector type
case type
when :datetime
proc { |val| val.is_a?(Time) ? (val.getgm + 8.hours).strftime("%Y-%m-%d %H:%M:%S") : val}
else
proc { |val| val }
end
end
......
......@@ -94,12 +94,12 @@ RSpec.describe WeatherModel do
it 'test Ohm to_h' do
ohm_obj = WeatherModel::Aqi::AqiLive::Ohm.all.first
expect(ohm_obj.time_point.class).to eq(Time)
expect(ohm_obj.time_point.class).to eq(String)
expect(ohm_obj.aqi.class).to eq(Integer)
expect(ohm_obj.co.class).to eq(Float)
expect(ohm_obj.area.class).to eq(String)
hash = ohm_obj.to_h
expect(hash[:time_point].class).to eq(Time)
expect(hash[:time_point].class).to eq(String)
expect(hash[:aqi].class).to eq(Integer)
expect(hash[:co].class).to eq(Float)
expect(hash[:area].class).to eq(String)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment