原创作者: hideto   阅读:1676次   评论:0条   更新时间:2011-05-26    
Rails宝典之第二式: 动态find_by方法

忘了声明了,这个系列主要是Rails入门教学。

今天Rails宝典教大家的是动态find_by方法,我们先看一段代码:
class TasksController < ApplicationController

  def incomplete
    @tasks = Task.find(:all, :conditions => ['complete = ?', false])
  end

end

很类似Hibernate的数据库查询hql语句,但显然我们的Rails不可能这么逊,看看改良的方法:
class TasksController < ApplicationController

  def incomplete
    @tasks = Task.find_all_by_complete(false)
  end

end

我们的Task这个Model类没有定义find_all_by_complete啊,我们为什么可以调用这个方法呢?

请看active_record/base.rb中的一段代码:
def method_missing(method_id, *arguments)
  if match = /^find_(all_by|by)_([_a-zA-Z]\w*)$/.match(method_id.to_s)
    finder = determine_finder(match)

    attribute_names = extract_attribute_names_from_match(match)
    super unless all_attributes_exists?(attribute_names)

    attributes = construct_attributes_from_arguments(attribute_names, arguments)

    case extra_options = arguments[attribute_names.size]
      when nil
        options = { :conditions => attributes }
        set_readonly_option!(options)
        ActiveSupport::Deprecation.silence { send(finder, options) }

      when Hash
        finder_options = extra_options.merge(:conditions => attributes)
        validate_find_options(finder_options)
        set_readonly_option!(finder_options)

        if extra_options[:conditions]
          with_scope(:find => { :conditions => extra_options[:conditions] }) do
            ActiveSupport::Deprecation.silence { send(finder, finder_options) }
          end
        else
          ActiveSupport::Deprecation.silence { send(finder, finder_options) }
        end

      else
        raise ArgumentError, "Unrecognized arguments for #{method_id}: #{extra_options.inspect}"
    end
  elsif match = /^find_or_(initialize|create)_by_([_a-zA-Z]\w*)$/.match(method_id.to_s)
    instantiator = determine_instantiator(match)
    attribute_names = extract_attribute_names_from_match(match)
    super unless all_attributes_exists?(attribute_names)

    if arguments[0].is_a?(Hash)
      attributes = arguments[0].with_indifferent_access
      find_attributes = attributes.slice(*attribute_names)
    else
      find_attributes = attributes = construct_attributes_from_arguments(attribute_names, arguments)
    end
    options = { :conditions => find_attributes }
    set_readonly_option!(options)

    find_initial(options) || send(instantiator, attributes)
  else
    super
  end
end

def extract_attribute_names_from_match(match)
  match.captures.last.split('_and_')
end

看看第一行代码:if match = /^find_(all_by|by)_([_a-zA-Z]\w*)$/.match(method_id.to_s)
这是一个正则表达式匹配:
^匹配一行的开始
$匹配一行的结束
\w匹配一个词语,可以是数字、字母、下划线
[]匹配括号里面符合的一个字符
*匹配0个或多个它前面的字符或短语
则([_a-zA-Z]\w*)则匹配以下划线或任意小写字母或任意大写字母开头的一个字符串
具体参考《Programming Ruby》中的Regular Expressions一章

而extract_attribute_names_from_match方法也很有意思,match.captures返回匹配的字符串组成的数组,last返回最后一个元素,如:
/^(a)_(b)_(\w*)$/.match("a_b_c_d_e_f_g").captures # => ["a", "b", "c_d_e_f_g"]
/^(a)_(b)_(\w*)$/.match("a_b_c_d_e_f_g").captures.last # =>"c_d_e_f_g"
/^find_(all_by|by)_([_a-zA-Z]\w*)$/.match("find_by_a_and_b_and_c").captures.last # => "a_and_b_and_c"


这样,第一行代码所匹配的方法名具体为find_by(或all_by)_aaaBBB形式
而extract_attribute_names_from_match允许我们匹配形式为find_by(或all_by)_aaaBBB_and_cccDDD_and_eeeFFF_and_...的方法
即我们可以无限添加查询条件,通过_and_连接字段名即可

而且可以看出,我们还可以调用find_by_columnName、find_or_initialize_by_columnName、find_or_create_by_columnName等动态方法。
参考Rails源码研究之ActiveRecord:一,基本架构、CRUD封装与数据库连接

总结:
动态语言可以做出很强大的框架,完成很多有意思的工作,这是Java、C#这种静态语言望尘莫及的。
本例中的find_by方法就是利用Ruby的method_missing语法特性来为Model动态生成方法,我们可以称其为POJO增强

JavaScript也是一门大家可能忽略了但又十分强大的动态语言,参考Ruby和Python,JavaScript还有很大潜力可挖。
评论 共 0 条 请登录后发表评论

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics