美文网首页Ruby & Rails
rails中定义属性方法

rails中定义属性方法

作者: auguszou | 来源:发表于2016-10-27 00:44 被阅读55次

最近在开发token系统的过程中,需要在数据库中定义许多boolean值的字段,用来验证用户的这个token时候具有xx操作权限,按照ruby的惯例,一般不会如下来定义类的。

# Table name: tokens
#
# id
# token_hash
# read           :boolean
# write          :boolean
# ...

class Token < ActiveRecord::Base
    def read?
        read
    end
    def write?
        write
    end
end

这样定义不符合ruby的DRY原则。那么又该如何设计呢?
ruby有一个method_missing 的话,当你调用 Token.new.read? 方法时,该方法并没有定义,ruby就会调用 method_missing 方法,实现如下。

# 字段同上
class Token < ActiveRecord::Base
    FIELDS = ["read", "write"]
    def method_missing(m, *args, &block)
        if FIELDS.include?(m[0...-1]) && m[-1] == "?"
            self.send(m[0...-1], *args, &block)
        else
            raise NoMethodError.new("undefined method '#{m}' for #{inspect}:#{self.class}")
        end
    end

  def respond_to?(m, include_private = false)
     if if FIELDS.include?(m[0...-1]) && m[-1] == "?"
         true
     else
         super
     end
  end
end

method_missing写法又不太优雅,而且send调用方法比调用已定义方法慢很多。
ruby一个吸引人的地方在于它的元编程,可以动态的改变类和对象的结构。可以在类定义时使用define_method给类添加方法。
来使用define_method改良一下上述method_missing慢的问题。

# 字段同上
class Token < ActiveRecord::Base
    FIELDS = ["read", "write"]
    def method_missing(m, *args, &block)
         if FIELDS.include?(m[0...-1]) && m[-1] == "?"
              self.class.send :define_method, m do
                  self.send(m[0...-1])
              end
              self.send(m)
         end
    end
end

改良之后更加觉得别扭。
直接使用define_method来定义类。

# 字段同上
class Token < ActiveRecord::Base
    FIELDS = [:read, :write]
    FIELDS.each do |name| 
        define_method("#{name}?") do 
            send(name)
        end
    end
end

在rails中有更方便的定义属性方法的方式。使用define_attribute_methods 来定义属性方法,这真是棒极了。

# 字段同上
class Token < ActiveRecord::Base
    inlcude ActvieModel::AttributeMethods

    attribute_method_suffix '?'
    define_attribute_methods = [:read, :write]
end

还有你不仅可以通过这种方式定义后缀属性方法,还可以定义前缀属性方法甚至有前缀和后缀的属性方法。如attribute_method_prefix 或者attribute_method_affix

# 字段同上
class Token < ActiveRecord::Base
    inlcude ActvieModel::AttributeMethods

    attribute_method_affix prefix: 'enable_', suffix: '?'                                    
    define_attribute_methods [:read, :write]
end

Token.new.enable_read?

值得注意的是,在调用define_attribute_methods之前必须有attribute_method_prefix, attribute_method_suffixattribute_method_affix声明。

相关文章

  • rails中定义属性方法

    最近在开发token系统的过程中,需要在数据库中定义许多boolean值的字段,用来验证用户的这个token时候具...

  • 读、画 UML 类图

    一、表示类的属性和方法 类中包括属性和方法。属性定义的形式:可见性 名称 : 类型 [= 缺省值]方法定义的形式:...

  • 3. methods方法

    methods属性是定义方法的主要区域,在此属性中,可以定义各种自定义函数名的方法以及参数 练习1: 从练习中可以...

  • Python基础语法(八)面向对象

    类定义 类中包含属性和方法,类通过class来定义 不用定义属性,属性在每个对象中是独立的 对象包含对象 隐藏对象...

  • computed深入

    计算属性set/get 计算属性 (单向)在computed属性对象中定义计算属性的方法,在页面使用{{方法名}}...

  • javaScript创建对象的几种方式

    1.工厂方式 说明:1.在函数中定义对象,并定义对象的各种属性,,虽然属性可以为方法,但是建议将属性为方法的属性定...

  • swift --1 extension扩展

    swift 中的扩展可以: 添加计算型属性和计算型静态属性 定义实例方法和类型方法 提供新的构造器 定义下标 定义...

  • 枚举

    定义枚举类 可以在枚举中定义普通方法和抽象方法. 也同样可在枚举类中定义属性,构造方法. 实现原理 Java文件在...

  • Swift 扩展(extension)详解

    在Swift中扩展可以: 添加计算实例属性和计算类型属性; 定义实例方法和类型方法; 提供新构造器; 定义下标; ...

  • 自定义View之CustomImageView

    自定义View的步骤: 自定义VIew的属性 在VIew的构造方法中获得我们的属性 重写OnMeasure方法 重...

网友评论

本文标题:rails中定义属性方法

本文链接:https://www.haomeiwen.com/subject/qhujuttx.html