新手问题 我需要组装一个复杂的对象,不知道有没更好的实现方式

sanvi · 2015年11月05日 · 最后由 xiaoronglv 回复于 2015年11月07日 · 1959 次阅读

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)

像 form_helper 那样如何

至少把需求和设计思路说下吧…… 不贴代码是耍流氓,但是只贴代码也是耍流氓啊。

#2 楼 @darkbaby123 哈哈哈,我打算组装一个这样的对象,Template 里面一个模板,含headerbodybody其实是一个Card的数组, Card的 new 如上图那样

Ruby Weekly 曾推荐过一篇关于 Data Ojbect 文章,能帮上楼主的忙吗?

http://brewhouse.io/2015/07/31/be-nice-to-others-and-your-future-self-use-data-objects.html

class Card
  include Virtus.model

  attribute :url, String 
  attribute :data, String
  attribute :type, String
  attribute :style, String
  attribute :id, Integer
end

class Header
  include Virtus.model

  attribute :title, String
  attribute :menu, String
  attribute :icon, String
end


class Template
  include Virtus.model

  attribute :menu, String
  attribute :cards, Array[Card]
end


Card.new(card_params)
Header.new(head_params)
Template.new()
需要 登录 后方可回复, 如果你还没有账号请 注册新账号