`
guodongbuding
  • 浏览: 38669 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

composed_of

阅读更多
class NetworkResource < ActiveRecord::Base
    composed_of :cidr,
                :class_name => 'NetAddr::CIDR',
                :mapping => [ %w(network_address network), %w(cidr_range bits) ],
                :allow_nil => true,
                :constructor => Proc.new { |network_address, cidr_range| NetAddr::CIDR.create("#{network_address}/#{cidr_range}") },
                :converter => Proc.new { |value| NetAddr::CIDR.create(value.is_a?(Array) ? value.join('/') : value) }
  end

  # This calls the :constructor
  network_resource = NetworkResource.new(:network_address => '192.168.0.1', :cidr_range => 24)

  # These assignments will both use the :converter
  network_resource.cidr = [ '192.168.2.1', 8 ]
  network_resource.cidr = '192.168.0.1/24'

  # This assignment won't use the :converter as the value is already an instance of the value class
  network_resource.cidr = NetAddr::CIDR.create('192.168.2.1/8')

  # Saving and then reloading will use the :constructor on reload
  network_resource.save
  network_resource.reload
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics