ruby module extend self

Posted by wxianfeng Tue, 14 Jul 2009 17:39:00 GMT

环境:ruby 1.9.2 + ubuntu 10.10 + rails 3.0.3

我们知道 ruby 中 扩展class ,写公用方法 ,或者 利用命名空间 来模块化 ,都是通过 module 来实现的 , 今天 看 rails 中 camelize 方法的源码的时候 , 发现 module 这样写的…..

active_support/inflector/methods.rb

module ActiveSupport
  # The Inflector transforms words from singular to plural, class names to table names, modularized class names to ones without,
  # and class names to foreign keys. The default inflections for pluralization, singularization, and uncountable words are kept
  # in inflections.rb.
  #
  # The Rails core team has stated patches for the inflections library will not be accepted
  # in order to avoid breaking legacy applications which may be relying on errant inflections.
  # If you discover an incorrect inflection and require it for your application, you'll need
  # to correct it yourself (explained below).
  module Inflector
    extend self

    # By default, +camelize+ converts strings to UpperCamelCase. If the argument to +camelize+
    # is set to <tt>:lower</tt> then +camelize+ produces lowerCamelCase.
    #
    # +camelize+ will also convert '/' to '::' which is useful for converting paths to namespaces.
    #
    # Examples:
    #   "active_record".camelize                # => "ActiveRecord"
    #   "active_record".camelize(:lower)        # => "activeRecord"
    #   "active_record/errors".camelize         # => "ActiveRecord::Errors"
    #   "active_record/errors".camelize(:lower) # => "activeRecord::Errors"
    #
    # As a rule of thumb you can think of +camelize+ as the inverse of +underscore+,
    # though there are cases where that does not hold:
    #
    #   "SSLError".underscore.camelize # => "SslError"
    def camelize(lower_case_and_underscored_word, first_letter_in_uppercase = true)
      if first_letter_in_uppercase
        lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
      else
        lower_case_and_underscored_word.to_s[0].chr.downcase + camelize(lower_case_and_underscored_word)[1..-1]
      end
    end

    # Makes an underscored, lowercase form from the expression in the string.
    #
    # Changes '::' to '/' to convert namespaces to paths.
    #
    # Examples:
    #   "ActiveRecord".underscore         # => "active_record"
    #   "ActiveRecord::Errors".underscore # => active_record/errors
    #
    # As a rule of thumb you can think of +underscore+ as the inverse of +camelize+,
    # though there are cases where that does not hold:
    #
    #   "SSLError".underscore.camelize # => "SslError"
    def underscore(camel_cased_word)
      word = camel_cased_word.to_s.dup
      word.gsub!(/::/, '/')
      word.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2')
      word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
      word.tr!("-", "_")
      word.downcase!
      word
    end

    # Replaces underscores with dashes in the string.
    #
    # Example:
    #   "puni_puni" # => "puni-puni"
    def dasherize(underscored_word)
      underscored_word.gsub(/_/, '-')
    end

    # Removes the module part from the expression in the string.
    #
    # Examples:
    #   "ActiveRecord::CoreExtensions::String::Inflections".demodulize # => "Inflections"
    #   "Inflections".demodulize                                       # => "Inflections"
    def demodulize(class_name_in_module)
      class_name_in_module.to_s.gsub(/^.*::/, '')
    end

    # Creates a foreign key name from a class name.
    # +separate_class_name_and_id_with_underscore+ sets whether
    # the method should put '_' between the name and 'id'.
    #
    # Examples:
    #   "Message".foreign_key        # => "message_id"
    #   "Message".foreign_key(false) # => "messageid"
    #   "Admin::Post".foreign_key    # => "post_id"
    def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
      underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id")
    end

    # Ruby 1.9 introduces an inherit argument for Module#const_get and
    # #const_defined? and changes their default behavior.
    if Module.method(:const_get).arity == 1
      # Tries to find a constant with the name specified in the argument string:
      #
      #   "Module".constantize     # => Module
      #   "Test::Unit".constantize # => Test::Unit
      #
      # The name is assumed to be the one of a top-level constant, no matter whether
      # it starts with "::" or not. No lexical context is taken into account:
      #
      #   C = 'outside'
      #   module M
      #     C = 'inside'
      #     C               # => 'inside'
      #     "C".constantize # => 'outside', same as ::C
      #   end
      #
      # NameError is raised when the name is not in CamelCase or the constant is
      # unknown.
      def constantize(camel_cased_word)
        names = camel_cased_word.split('::')
        names.shift if names.empty? || names.first.empty?

        constant = Object
        names.each do |name|
          constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name)
        end
        constant
      end
    else
      def constantize(camel_cased_word) #:nodoc:
        names = camel_cased_word.split('::')
        names.shift if names.empty? || names.first.empty?

        constant = Object
        names.each do |name|
          constant = constant.const_defined?(name, false) ? constant.const_get(name) : constant.const_missing(name)
        end
        constant
      end
    end

    # Turns a number into an ordinal string used to denote the position in an
    # ordered sequence such as 1st, 2nd, 3rd, 4th.
    #
    # Examples:
    #   ordinalize(1)     # => "1st"
    #   ordinalize(2)     # => "2nd"
    #   ordinalize(1002)  # => "1002nd"
    #   ordinalize(1003)  # => "1003rd"
    def ordinalize(number)
      if (11..13).include?(number.to_i % 100)
        "#{number}th"
      else
        case number.to_i % 10
          when 1; "#{number}st"
          when 2; "#{number}nd"
          when 3; "#{number}rd"
          else    "#{number}th"
        end
      end
    end
  end
end

发现 了这样的写法

module A
module B
extend self
.....
end
end

extend self 有何作用?

先来看个demo:

module Foo
  module Bar
      extend self # self => Foo::Bar

    def hello
      p "hello"
    end
  end
end

class Klass
  include Foo::Bar
end

Klass.new.hello #  "hello"
Foo::Bar.hello # "hello"
Klass.hello # undefined method `hello' for Klass:Class (NoMethodError)

发现 module 中的方法 可以当作模块方法 直接被Module调用 , 被include 到class 中后 , 依然还是 class 的实例方法 , 恩,不错,以后 像下面 这样的写法, 都要 改改了:

module A
def self.foo
end
end

改成这样:

module A
extend self
def foo
end
end

demo里的extend self 其实就是 Foo::Bar.extend(Foo::Bar)

所以 可以 更动态的 写成这样:

module Foo
  module Bar     

    def hello
      p "hello"
    end
  end
end

class Klass
  include Foo::Bar
end

Foo::Bar.extend(Foo::Bar)

Klass.new.hello #  "hello"
Foo::Bar.hello # "hello"
Klass.hello # undefined method `hello' for Klass:Class (NoMethodError)

see:
http://www.railsfire.com/article/extending-self-module


rails check_box_tag boolean

Posted by wxianfeng Tue, 30 Jun 2009 16:16:00 GMT

环境:ruby 1.9.2 + rails 3.0.3 + ubuntu 10.10

scaffold 生成的 form_for 对应的 boolean 类型 是check_box , 数据库中 值是 1 check_box就选中, 是 0 就不选中, 但是不是 form_for 的话 ,check_box_tag 怎么实现呢

仿照 form_for check_box 生成的代码:

<input name="user[abc]" type="hidden" value="0" />
<input checked="checked" id="user_abc" name="user[abc]" type="checkbox" value="1" />

可以看出 多生成了 一段 hidden , 为什么 ?

因为 check_box 的工作原理是 :

选中了 就传check_box 的参数 , 不选中 不传 check_box 的 参数

所以上面 选中的话,传的值是 1

没选中的话, 传的是 0

所以check_box_tag 的话,就应该这样写了.

     <%= hidden_field_tag "user[abc]" , 0 %>
      <%= check_box_tag "user[abc]" , 1 , (true if ele.abc == 1)  %>

注意 需要 添加 hidden 域 , 并且 需要在 checkbox 的上面