Commit f672f229 by ivan Lan

Add generate methods for value column and template column

parent 22ef5cd0
...@@ -5,22 +5,23 @@ module Shotengai ...@@ -5,22 +5,23 @@ module Shotengai
end end
class_methods do class_methods do
def custom_hash_columns *columns def custom_hash_columns columns, options={}
decode_or_not = options[:decode]
columns.each do |column| columns.each do |column|
# QUESTION: 这样可以避免 send("#{column}="), 合适? # QUESTION: 这样可以避免 send("#{column}="), 合适?
class_eval %Q{ class_eval %Q{
define_method('#{column}') do define_method('#{column}') do
super() || {} super() || {}
end end
if #{decode_or_not}
define_method("#{column}_input=") do |val|
parsed_val = val && val.map{ |h| { (h[:key] || h['key']) => (h[:val] || h['val']) } }.reduce(&:merge)
self.#{column} = parsed_val
end
define_method("#{column}_input=") do |val| define_method("#{column}_output") do
parsed_val = val && val.map{ |h| { (h[:key] || h['key']) => (h[:val] || h['val']) } }.reduce(&:merge) self.#{column}.map {|key, val| { key: key, val: val } }
self.#{column} = parsed_val end
self.#{column}_will_change!
end
define_method("#{column}_output") do
self.#{column}.map {|key, val| { key: key, val: val } }
end end
} }
end end
...@@ -30,6 +31,36 @@ module Shotengai ...@@ -30,6 +31,36 @@ module Shotengai
# like meta, detail these json using for code development # like meta, detail these json using for code development
end end
def generate_hash_template_column_for names
names.each do |name|
class_eval %Q{
def #{name}_value
Shotengai::Harray.new(super())
end
def #{name}_value= val
raise Shotengai::WebError.new('#{name}_val 必须是个 Array'), -1 , 401) unless val.nil? || Array === val
super(val)
end
}
end
end
def generate_hash_value_column_for names, options={}
names.each do |name|
class_eval %Q{
delegate :#{name}_template, to: :#{options[:delegate_template_to]} if self.respond_to?(#{options[:delegate_template_to]})
def #{name}
{
template: self.#{name}_template,
value: self.#{name}_value,
}
end
}
end
end
def column_has_children column, options def column_has_children column, options
ArgumentError.new("Please give #{column} one child at least.") unless options[:children] ArgumentError.new("Please give #{column} one child at least.") unless options[:children]
children_names = options[:children].map(&:to_s) children_names = options[:children].map(&:to_s)
......
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