`
52jobs
  • 浏览: 10985 次
最近访客 更多访客>>
社区版块
存档分类
最新评论

理解rails gems plugins

 
阅读更多
#33 Making a Plugin
引用
注意 这种手法,可能对 rails 4 不再起作用
rails4 http://guides.rubyonrails.org/plugins.html

关于废弃插件的说明 https://github.com/rails/rails/commit/dad7fdc5734a3813246f238ac5760b2076932216
rails 3及以下
After loading the framework and any gems and plugins in your application, Rails turns to loading initializers. An initializer is any Ruby file stored under +config/initializers+ in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks, plugins and gems are loaded, such as options to configure settings for these parts.
rails4
After loading the framework and any gems in your application, Rails turns to loading initializers. An initializer is any Ruby file stored under +config/initializers+ in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks and gems are loaded, such as options to configure settings for these parts.

rails4 不再有 vendor/plugins
Rails 4 将删除 Rails::Plugins 类,所以将不会再加载 vender/plugins 目录下的任何代码。
大多数应用应该依赖于 gems 而不是插件。但如果你在 vender/plugins 中还有一些代码,你有两种选择:
改用 gem 方式实现,多数插件已经有了 gem 版本,如果没有你可以在 Gemfile 中通过 :gitor:pathoptions 来引用插件
移到 lib/your\_pluginand ,然后在 conconfig/initializers 初始化


简介:将get/set等做成一个plugin 减少重复
 You can sometimes remove a lot of duplication by generating methods dynamic.
 In this episode I will show you how to create a plugin which does exactly that.
 
  目的: 
 class Task < ActiveRecord::Base
    belongs_to :project
     def due_at_string
       due_at.to_s(:db)
     end
  
     def due_at_string=(due_at_str)
       self.due_at = Time.parse(due_at_str)
     rescue ArgumentError
       @due_at_invalid = true
     end
end
 将以上代码简化成
 class Task < ActiveRecord::Base   
   stringify_time :due_at     
 end
 
 
 手法:
 1、script/generate plugin stringify_time

 2、init.rb
 require 'stringify_time'
 
 class ActiveRecord::Base
   extend StringifyTime
 end
 
 3、stringify_time.rb
  module StringifyTime
    def stringify_time(*names)
      names.each do |name|
      
        define_method "#{name}_string" do
          read_attribute(name).to_s(:db)
        end
      
        define_method "#{name}_string=" do |time_str|
          begin
            write_attribute(name, Time.parse(time_str))
          rescue ArgumentError
            instance_variable_set("@#{name}_invalid", true)
          end
        end      
        define_method "#{name}_is_invalid?" do
          return instance_variable_get("@#{name}_invalid")
        end      
      end
    end
  end

 4、 最终,我们的task model可以这样写
  class Task < ActiveRecord::Base
    belongs_to :project
    stringify_time :due_at  
    def validate
      errors.add(:due_at, "is invalid") if @due_at_invalid
    end  
  end
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics