Ruby类中“属性”的性质是什么?

在下面的例子中,我不理解像attr_readerproperty这样的关键字:

class Voiture 
  attr_reader :name
  attr_writer :name
  property :id, Serial
  property :name, String
  property :completed_at, DateTime
end

他们如何工作? 我如何创建自己的? 它们是功能还是方法?

class MyClass 
    mymagickstuff :hello
end

这只是类方法。 在这个例子中, has_foo向放置字符串的实例添加一个foo方法:

module Foo
  def has_foo(value)
    class_eval <<-END_OF_RUBY, __FILE__, __LINE__ + 1
      def foo
        puts "#{value}"
      end
    END_OF_RUBY
  end
end

class Baz
  extend Foo
  has_foo 'Hello World'
end

Baz.new.foo   # => Hello World

这些是类方法,可以将它们添加到类中,也可以创建自己的具有添加方法的类。 在你自己的班级里:

class Voiture
  def self.my_first_class_method(*arguments)
    puts arguments
  end
end

或者添加到课程中:

Voiture.class_eval do
  define_method :my_second_class_method do |*arguments|
    puts arguments
  end
end

一旦定义了这样的类方法,就可以像这样使用它:

class VoitureChild < Voiture

    my_first_class_method "print this"

    my_second_class_method "print this"

end

还有一些方法可以通过向类中添加模块来实现,这通常是rails如何执行这些操作,例如使用Concern


你会想猴子补丁类Module 。 这就是attr_reader这样的方法所在。

class Module
  def magic(args)
     puts args.inspect
  end
end

class A
  magic :hello, :hi
end
#=> [:hello, :hi]

正如锡文提到的那样,猴子修补基础班级可能是危险的。 考虑它像是时间 - 去往过去并添加过去的东西。 只要确保你添加的内容不会覆盖其他事件,否则你可能会回到Ruby脚本/时间轴上,这与你离开的不一样。

链接地址: http://www.djcxy.com/p/25789.html

上一篇: What's the nature of "property" in a Ruby class?

下一篇: Ruby constructor self vs @