代码之家  ›  专栏  ›  技术社区  ›  Gavin Yap

Ruby Mixins属性

  •  0
  • Gavin Yap  · 技术社区  · 10 年前

    受datamapper如何使用mixin的启发,我需要了解如何使用mixen复制以下内容

    module Property
      def property(name, type, value)
        #Some code
      end
    end
    
    class Weapon 
      include Property
    
      property :name, :string, "The legendary Sword"
      property :attack, :integer, 10
    end
    
    class Item
      include Property
    
      property :name, :string, "Magic Carpet"
      property :description, :string, "Fly you to the moon"
    end
    

    但我有个错误,

    NoMethodError: undefined method `property' for Route:Class
    

    任何帮助都非常感谢。谢谢

    2 回复  |  直到 10 年前
        1
  •  2
  •   Arie Xiao    10 年前

    默认情况下,如果您 include Property 在另一个类中,所有实例方法作为实例方法对其他类的实例可用。

    在您的情况下,您可以使用 extend Property 在另一个类中 Property 成为其他类的类方法。

    module Property
      def property(name, type, value)
        #Some code
      end
    end
    
    class Weapon 
      extend Property
    
      property :name, :string, "The legendary Sword"
      property :attack, :integer, 10
    end
    

    或者如果您喜欢使用 包括属性 ,您可以将模块的 included 方法,并在那里添加必要的方法。

    module Property
      def self.included(clazz)
        clazz.define_singleton_method(:property) do |name, type, value|
          p [name, type, value]
        end
      end
    end
    
        2
  •  0
  •   Gavin Yap    10 年前

    所以在关注了Arie的帖子之后,这就是我所做的

    module Item
      def self.included(item)
        item.extend Property
      end         
    end
    
    module Property
    def property(name, type, value)
      define_method(name) { p [name, type, value] }
    end
    
    class Weapon 
      include Item
    
      property :name, :string, "The legendary Sword"
      property :attack, :integer, 10
    end