Sha256: 1874467535ba7d3a3b60bf08231e5fc81d839c561d1eeab449def51aac51a09b

Contents?: true

Size: 1.04 KB

Versions: 1

Compression:

Stored size: 1.04 KB

Contents

module OxMlk
  class Attr
    PROCS = (Hash.new {|h,k| k.to_proc rescue nil}).merge(
      Integer => :to_i.to_proc,
      Float => :to_f.to_proc,
      String => :to_s.to_proc,
      Symbol => :to_sym.to_proc,
      :bool => proc {|a| fetch_bool(a)})
    
    attr_reader :accessor, :setter,:from, :as, :procs, :tag_proc, :tag
    
    def initialize(name,o={},&block)
      name = name.to_s
      @accessor = name.chomp('?').intern
      @setter = "#{@accessor}=".intern
      @from = o[:from]
      @tag_proc = o[:tag_proc].to_proc rescue proc {|x| x}
      @tag = (from || (@tag_proc.call(accessor.to_s) rescue accessor)).to_s
      @as = o[:as] || (:bool if name.ends_with?('?'))
      @procs = ([*as].map {|k| PROCS[k]} + [block]).compact
    end
    
    def from_xml(data)
      procs.inject(XML::Node.from(data)[tag]) {|d,p| p.call(d) rescue d}
    end
    
    def self.fetch_bool(value)
      value = value.to_s.downcase
      return true if %w{true yes 1 t}.include? value
      return false if %w{false no 0 f}.include? value
      value
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
oxmlk-0.3.2 lib/oxmlk/attr.rb