hi,各位,我打算组装一个这样的对象,Template 里面一个模板,含 header 跟 body,body 其实是一个 Card 的数组,Card 的 new 如下图那样 不知道有没更好的实现方式
//card.rb
class Card
attr_accessor :url, :data, :type, :style, :id
def initialize(params)
params.each do |key, value|
instance_variable_set("@#{key}", value)
end
end
end
//header.rb
class Header
attr_accessor :title, :menu, :icon
def initialize(params)
params.each do |key, value|
instance_variable_set("@#{key}", value)
end
end
end
//style.rb
class Style
attr_accessor :margin_top, :margin_right, :margin_bottom, :margin_left, :background
def initialize(params)
params.each do |key, value|
instance_variable_set("@#{key}", value)
end
end
end
//template.rb
class Template
attr_accessor :header, :body
def initialize(params)
params.each do |key, value|
instance_variable_set("@#{key}", value)
end
end
def add_card(card)
@body ||= Array.new
@body << card
self
end
end
//这里是组装对象
nameView = Card.new(:data => JSON.parse(File.read("#{Rails.root}/user.json")),:type => "NameItemCard", :style => Style.new(:margin_top => 10),:id => "nameCard")
itemView = Card.new(:data => JSON.parse(File.read("#{Rails.root}/setting_item.json")),:type => "ItemDividerCard",:style => Style.new(:margin_top => 10), :id => "itemCard")
buttonView = Card.new(:data => JSON.parse(File.read("#{Rails.root}/setting_button.json")),:type => "MatchButtonCard", :style => Style.new(:margin_top => 30), :id => "btnLogout")
header = Header.new(:title => "我的", :icon => "ic_tab_me_normal")
template = Template.new(:header => header).add_card(nameView).add_card(itemView).add_card(buttonView)