`
xxj
  • 浏览: 430042 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Simplest Ruby BeanUtils:)

阅读更多
module BeanUtils
  RESERVE_INSTANCE_KEY = %w{id attributes_cache new_record}
  #copy properties

  def cp(dest)
    dest = dest.new if dest.is_a?(Class)

    copy = lambda{|h| h.each{|key, value| dest.send("#{key}=", value) if dest.respond_to?("#{key}=") and !value.blank?}}

    returning dest do
      self.instance_values.each do |key, value|
        unless RESERVE_INSTANCE_KEY.include? key
           
          if value.is_a? Hash
            #copy attributes
            copy.call(value)
          else
            #copy other instance values
            copy.call({key=>value})
          end
        end
      end
    end
  end
end



Usage:

topic = Topic.new params[:topic]
post = topic.cp(Post)


Any other useful methods?

http://commons.apache.org/beanutils/apidocs/index.html

pls do it yourself:)
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics