Archive for category Ruby On Rails

体验rails-3 ActiveModel

active_model是rails3新添加的一个模块,主要功能是让ruby对象都能像active_record一样使用

1.validation

 class User
   include ActiveModel::Validations
   attr_accessor :first_name,:last_name
 
   validates_presence_of :first_name,:last_name
 
 end
 
 p1 = User.new
 
 p1.errors  # => <OrderedHash {:first_name=>["can't be blank"],
            #:last_name=>["can't be blank"]}>
 p1.valid?  # => false

也可以这样使用

# models/user_validator.rb
class UserValidator < ActiveModel::Validator
  def validate(record)
    record.errors[:base] = "invalid name lenght" if record.name.length > 20
  end
end
# models/user.rb
class User < ActiveRecord::Base
  include UserValidator
  validate_with MyValidator
end

2.attributes
平常我们给类对象定义属性的时候一般都用attr_accessor一类的方法,active_model提供了

define_attribute_methods一系列的方法
class User
  include ActiveModel::AttributeMethods
  attribute_method_affix  :prefix => 'prefix_', :suffix => '_suffix'

  define_attribute_methods [:name]
end

user = User.new
user.methods.grep /prefix_name/  
# => ["prefix_name_suffix"] 但是调用这个方法的时候会出错,期望beta过后能修正

3.callbacks
callbacks很简单,与active_record类差不多,只是实现需要调用callbacks方法里面加上一个block

class UserCallbacks
  def self.before_save(obj)
    p "before_save call"
  end
end

class User
  extend ActiveModel::Callbacks
 
  define_model_callbacks :save,:only => :before

  def save
    _run_save_callbacks do
      p "call save method"
    end
  end

  # before_save UserCallbacks 这种方式也可以使用
  # 这个应该是datamapper里面的风格,active_record里没见过
  before_save :save_callbacks

  protected
 
  def save_callbacks
    p "save_callbacks call"
  end
end

没有评论

rails关键字过滤

从前了解关键字过滤以为就是普通正则表达式的循环,原来关键词的过滤也是有算法的!!!
下面是一个简单的实现的dfa词法树,写给一个论坛板块做关键词过滤的,随着关键词的递增,耗时与正则表达式比起来要节约很多

class WordReplacement < ActiveRecord::Base

  def self.replacement_hash
    Hash[*all.collect{|re| [re.regex_str,re.replacement] }.flatten]
  end

  def self.filter_word_tree(object = nil)
    word_tree = Array.new(256)
    word_tree << 0

    object = replacement_hash if object.nil?

    object.each do |word,replace|
      temp  = word_tree
      bytes = word.bytes.to_a
      len   = bytes.size

      bytes.each_with_index do |asicc_code,arr_index|
        if arr_index < len - 1
          if temp[asicc_code].nil?
            node = [Array.new(256),0]
            temp[asicc_code] = node
          elsif temp[asicc_code] == 1
            node = [Array.new(256),1]
            temp[asicc_code] = node
          else

          end
          temp = temp[asicc_code][0]
        else
          temp[asicc_code] = 1
        end # end if
      end # end bytes
    end # end word
    [word_tree,0]

  end


  def self.handle_word(do_words,replace = true,word_tree = nil,word_hash = nil)
    word_tree = filter_word_tree if word_tree.nil?
    word_hash = replacement_hash if word_hash.nil?
    temp      = word_tree
    nodeTree  = word_tree
    words     = []
    word      = []
    to_replace= []
    a         = 0
    while a < do_words.size
      index = do_words[a]
      temp = temp[0][index]
      if temp.nil?
        temp = nodeTree
        a = a - word.size
        word = []
        to_replace = []
      elsif temp == 1 or temp[1] == 1
        word << index
        to_replace << a
        words << word
       
        if replace
          replace_word = word_hash[asicc_code_to_s(word)]
          do_words[(a-to_replace.size + 1),to_replace.size] = replace_word
          a = (a - to_replace.size + 1) + (replace_word.size - 1)
        else
          a = a - word.size + 1
        end
        word = []
        to_replace = []
        temp = nodeTree
      else
        word << index
        to_replace << a
      end
      a += 1  
    end
    return do_words if replace
    words.collect{|e| e.collect{|ch|ch.chr}.join }
  end

  protected
  def self.asicc_code_to_s(words)
    words.collect{|e| e.chr }.join
  end

end

2 Comments

uninitialized constant MysqlCompat::MysqlRes

export ARCHFLAGS=”-arch i386 -arch x86_64″ ;sudo gem install –no-rdoc –no-ri
-v=2.7 mysql — –with-mysql-dir=/usr/local/mysql
–with-mysql-config=/usr/local/mysql/bin/mysql_config

64位的系统安装方法,装的时候其实主要找到mysql_config这个东西,我这里装的是2.7的gem

没有评论

rails sphinx全文检索

1.安装mmseg这个ruby中文分词的扩展

wget http://www.coreseek.cn/uploads/csft/3.1/Source/mmseg-3.1.tar.gz
    tar xzvf mmseg-3.1.tar.gz
    cd mmseg-3.1
    chmod a+x configure
    ./configure && make && make install

安装ruby扩展

cd ruby
    cp /usr/local/include/mmseg/*.h .
    cp ../src/*.h .
    cp ../src/css/*.h .
    ruby extconf.lin.rb
    make && make install
cd ../data
    mmseg -u unigram.txt
    将生成的词库重命名为uni.lib
    cp uni.lib ../ruby
    cd ../ruby
    ruby test.rb

如果运行成功的话,安装完毕了

2.安装 csft3.2

 wget http://www.coreseek.cn/uploads/csft/3.2/csft-3.2.12.tar.gz
    tar xzvf csft-3.2.12.tar.gz
    cd csft-3.2.12
    ./configure --with-mysql=/usr/local/mysql
    make && make install

3.安装sphinx插件
ruby script\plugin install git://github.com/freelancing-god/thinking-sphinx.git
注释掉: Rails.configuration.cache_classes = false,这个在我这里是第行

rake ts:config
vi config/development.sphinx.conf
将 charset_type = utf-8 改为 charset_type = zh_cn.utf-8
并且在下面添加:charset_dictpath = /usr/local/csft/var/data # 这里的意思是存放词库的地址,也就是刚刚使用mmseg -u生成的那个文件

4.测试

1 Comment

rails连接sqlserver2000,2005,2008

download unixODBC-2.3.0.tar.gz
tar xzvf unixODBC-2.3.0.tar.gz
cd unixODBC-2.3.0
./configure --enable-drivers
   --enable-driver-conf
   --enable-dependency-tracking
   --prefix=/usr/local/unixODBC
   --sysconfdir=/etc --enable-gui=no
make && make install
download freetds-0.82.tar.gz
tar xzvf freetds-0.82.tar.gz
cd freetds-0.82
./configure --enable-msdblib
       --sysconfdir=/etc/
       --with-unixodbc=/usr/local/unixODBC/
       --with-tdsver=8.0
       --prefix=/usr/local/freetds-with-unixodbc/
make && make install

download http://www.ch-werner.de/rubyodbc/ruby-odbc-0.9999.tar.gz
安装ruby的odbc扩展,千万不要下载0.9997

tar xzvf ruby-odbc-0.9999.tar.gz
cd ruby-odbc-0.9999
ruby extconf.rb --with-odbc-dir=/usr/local/unixODBC
  --ruby=/usr/local/bin/ruby
  --diable-dlopen
make && make install

/etc/odbc.ini

[HXDB]
Driver= FreeTDS
Description=ODBC connection via FreeTDS
Trace=yes
TraceFile=/tmp/odbc_tr
Servername=hxdb
Database=MR2000DB

/etc/odbcinst.ini

[FreeTDS]
Description=TDS driver (Sybase/MS SQL)
Driver=/usr/local/freetds-with-unixodbc/lib/libtdsodbc.so
FileUsage=1

odbc.ini和odbcinst.ini这两个文件每行都不要留空格或者制表格,不然的话会出错

/etc/freetds.conf(这里192.168.1.16是sqlserver的地址)

[hxdb]
    host = 192.168.1.16
    port = 1433
  client charset = UTF-8

安装rails连接mssql所需要的gem

gem install dbd-odbc
gem install dbi
gem install activerecord-sqlserver-adapter -v=2.3.8

我在公司最后一次写这样的安装文档………

没有评论