ruby1.9 char to ascii(int value)

Posted by wxianfeng Wed, 26 Aug 2009 20:20:00 GMT

环境 : ruby 1.9.2 + ruby 1.8.7

ruby 1.8 时代 char to ascill 一般这么做:

"a"[0]  # 97
?a # 97

但是 1.9 时代 该方法 不可以了,输出如下:

"a"[0] # a
?a # a

后来 我用了 一个 变态的 方法:

"a".bytes.to_a.first # 97

1.9 时代 应该使用ord 函数

"a".ord  # 97
"a"[0].ord # 97
?a.ord # 97

ascill to char 通用:

97.chr # "a"

但是 ord 函数 1.8 环境下 同样可以使用;

看下 ord 函数的源码(built in 方法,内部看不到ruby代码):

  #     int.ord    => int
  #
  #
  # Returns the int itself.
  #
  #    ?a.ord    #=> 97
  #
  # This method is intended for compatibility to
  # character constant in Ruby 1.9.
  # For example, ?a.ord returns 97 both in 1.8 and 1.9.
  #
  #
  def ord
    # This is just a stub for a builtin Ruby method.
    # See the top of this file for more info.
  end

see:
http://stackoverflow.com/questions/1270209/getting-an-ascii-character-code-in-ruby-fails


Rails 动态生成表和Model

Posted by wxianfeng Sat, 01 Aug 2009 17:12:00 GMT

环境:ruby 1.9.2 + rails 3.0.3 + ubuntu 10.10

项目需要运行中动态生成表 和 Model , 怎么办 ?

借助 ActiveRecord::Migration 来实现 动态建表 和 字段

可以 借助 Object.const_set 来实现 动态Model

DEMO:

# RUN : rails runner lib/dynamic_table.rb

ActiveRecord::Migration.create_table :posts
ActiveRecord::Migration.add_column :posts, :title, :string

Object.const_set(:Post,Class.new(ActiveRecord::Base)) # => Object.class_eval { const_set(:Post,Class.new(ActiveRecord::Base)) }
# p Post.columns
p Post.column_names # ["id", "title"]

ActiveRecord::Migration.add_column :posts, :body, :text

p Post.column_names # ["id", "title"]

Object.class_eval { remove_const :Post }
Object.const_set(:Post,Class.new(ActiveRecord::Base))

p Post.column_names # ["id", "title", "body"]

动态Model 实质就相当于 Post = Class.new(ActiveRecord::Base) 或者 Post < ActiveRecord::Base

Class.new(ActiveRecord::Base) 参数指定 super_class , 默认是 Object

可以从ruby源码中看出:

  #     Class.new(super_class=Object)   =>    a_class
  #
  #
  # Creates a new anonymous (unnamed) class with the given superclass
  # (or <code>Object</code> if no parameter is given). You can give a
  # class a name by assigning the class object to a constant.
  #
  #
  #
  def self.new(super_class=Object)
    # This is just a stub for a builtin Ruby method.
    # See the top of this file for more info.
  end

当给表添加了新的字段后,Model 需要重新 const_set 一次 ,注意 const_set 之前 需要 remove_const 一次 , 不然会出现 已经初始化的警告

see:

http://hildolfur.wordpress.com/2006/10/29/class-reloading-in-ruby/