2010/05/20

self.send()[2]

http://midorex.blogspot.com/2010/05/selfsend.html
の続き。

  class Foo
    ary = [
      "Author", "Binding", "Creator",
      "EAN", "ISBN", "Label",
      "Manufacturer", "NumberOfPages",
      "ProductGroup", "ProductTypeName",
      "PublicationDate", "Publisher", "Studio",
      "Title", "MediumImage", "Price", "Edition",
      "Rank", "DetailPageURL", "Artist",
      "Format", "NumddberOfDiscs", "OriginalReleaseDate",
      "PackageQuantity", "ReleaseDate", "UPC", "RunningTime"
    ].each{|x| attr_accessor x.downcase.to_sym}

    def initialize(h)
      return nil unless h
      set_up(h)
      #@created ||= Time.now.to_s
    end

    def detail
      str = ""
      ins_a.each{|i| str << i.to_s.gsub("@",'').upcase + ":\s" + self[i] + "\n" }
      return str
    end

    def set_up(h)
      h.each{|k,v| 
        begin
          self.send("#{k.downcase.to_sym}=", v)
        rescue NoMethodError
          next # ignore new value.
        end
        }
    end

    # def detail needs [] and ins_a
    alias [] instance_variable_get
    alias ins_a instance_variables

    private :set_up, :[], :ins_a

  end
  h = {'Artist'=>'artist-name','Title'=>'music-title'}
  p Foo.new(h)


% ./test-item.rb
#<Foo:0x000000000 @artist="artist-name", @title="music-title">

h = {'Artist'=>'artist-name','Title'=>'music-title'}
h['noindex'] = 'noindex'
p Foo.new(h)
% ./test-item.rb
#<Foo:0x000000000 @artist="artist-name", @title="music-title">

git => github.com/midore/get_item_amzon

0 件のコメント: