2012-01-10 8 views
0

オブジェクト私は私のプロジェクトの一つでActiveModelを使用していると私は、動的メソッドのための最善の方法は、ActiveModel dymamic方法は

基本ActiveModelクラスのみ1つのアクセッサ属性が属性を呼び出した次のような状況で定義されたものをお聞きしたかったです。

def initialize(attributes = {}) 
     set_default_attributes! 
     @attributes.merge!(attributes.symbolize_keys) 
     @new_record = true  
    end 

    def read_attribute_for_validation(key) 
     @attributes[key] 
    end 


    def self.create(attributes={}) 
    obj = self.new(attributes) 
    obj.save 
    return obj 
    end 

    def save 
    if self.valid? 
     puts "saved!" 
     return true 
    end 
    return false 
    end  


    def update_attributes(attributes={}) 
    self.attributes.merge!(attributes.symbolize_keys) 
    self.save 
    end  



    def as_json(options={}) 
     hash = Hash.new 
     hash.merge!(self.attributes) 
     hash.as_json({:root=>false}.merge!(options || {})) 

    end 

方法は、アクセッサのようでなければならないが、@attributesがハッシュである場合{:param1=>1,:param2=>2}

インスタンス・オブジェクトは次のメソッドを

param1 
param1= 
param2 
param2= 

を有していなければならないように、私はしようとした可変

例内部@attributesを使用する必要がメソッドがありませんが、メソッドが "="で終わっている場合は、解析し、そのようなキーの属性をチェックする必要があります。コードの見た目が気に入らない。

+0

とメソッドを追加することができます!これは正規表現で簡単にできるはずです。 – phoet

+0

私はこれを行うことができますが、私はそれをより多くのルビーの方法にするためにdefine_methodを使いたいと思います – Fivell

+0

define_methodを使うのはもっとルビー的な方法だとは思っていませんが、早くやれよ?! – phoet

答えて

1

あなたがメソッド名から=を削除しない理由singleton_class.module_eval

def initialize(attributes = {}) 
    set_default_attributes! 
    @attributes.each do |key,value| 
    singleton_class.module_eval do 
     define_method(key) { self.attributes[key] } unless method_defined? key 
     define_method("#{key}=") { |new_value| self.attributes[key] = new_value } unless method_defined? "#{key}=" 
    end 
    end 
    @attributes.merge!(attributes.symbolize_keys) 
    @new_record = true 

end 
関連する問題