Ruby on Rails有用的插件 (2/106)

< 上一篇下一篇 >
本帖地址: 复制地址

修改 回帖 引用 楼主: CMO涔漠

用户形象图片

关键字:   ruby rails 插件    

<!-- Content Start -->

文件上传(FileColumn)
网页:
http://www.kanthak.net/opensource/file_column/
安装:http://opensvn.csie.org/rails_file_column/plugins/file_column

主题支持(Theme Support)
安装:
http://mattmccray.com/svn/rails/plugins/theme_support
动态的树型结构(LiveTree)
网页:
http://www.epiphyte.ca/code/live_tree.html
下载:http://www.epiphyte.ca/downloads/live_tree/live_tree-0.1.2.zip

国际化插件(Globalize)
网页:
http://wiki.globalize-rails.org/
安装:http://svn.globalize-rails.org/svn/globalize/globalize/trunk

本地化(Localization)
网页:
http://mir.aculo.us/articles/2005/10/03/ruby-on-rails-i18n-revisited
安装:http://dev.rubyonrails.org/svn/rails/plugins/localization/

文件上传进度显示(Rails Upload Progress)
网页:
http://wiki.rubyonrails.com/rails/pages/Upload+Progress+Bar
Demo:http://sean.treadway.info/demo/upload/

Rails引擎(Rails Engine)
网页:
http://rails-engines.org/
安装:http://svn.rails-engines.org/
包括LoginEngine, UserEngine,WikiEngine

索引搜索(Indexed Search)
网页:
http://lance.langwell-ball.com/pages/indexed-search
安装:http://langwell-ball.com/svn/indexed-search/

Ajax Scaffold生成器(Ajax Scaffold Generator)
网页:
http://ajaxscaffold.height1percent.com/
安装:gem install ajax_scaffold_generator

<!-- Content End -->
回到帖子顶部

回帖 引用 1楼[楼主] CMO涔漠

用户形象图片

[Ruby on Rails]Rails Login Engine和User Engine的使用

 
Rails Login Engine和User Engine提供了基本的用户登录,用户管理相关的功能,可以直接在应用程序中使用。

安装:

ruby script/plugin install http://svn.rails-engines.org/engines/trunk/

ruby script/plugin install http://svn.rails-engines.org/login_engine/trunk/

ruby script/plugin install http://svn.rails-engines.org/user_engine/trunk/

上面3个命令就分别安装好了所需的Engine。

相关的文档在:http://api.rails-engines.org/engines/

http://api.rails-engines.org/login_engine/

http://api.rails-engines.org/user_engine/

按照文档里面写的一步一步来就OK了。 

Login Generator plugin - README



= 开始之前

这是Rails Engine 版本的 Salted Login Generator,一个极好的登录系统,它足以满足大多数通常的需要。对于大多数部分,这个代码并没有修改它的生成器生成的表单,只有下面是例外
* 国际化部分被移除。
* 'welcome'页被换成了'home'页。
* 有少数功能被抛弃。

However, what I'm trying to say is that 99.9999% of the credit for this should go to Joe Hosteny, Tobias Luetke (xal) and the folks that worked on the original Salted Login generator code. I've just wrapped it into something runnable with the Rails Engine system.

Please also bear in mind that this is a work in progress, and things like testing are wildly up in the air... but they will fall into place very soon. And now, on with the show.


= 安装

安装 Login Engine 非常简单。

你的操作步骤是:
1. 做为一个 Rails 插件来安装:
$ script/plugin install login_engine
2. 使用 svn:externals
$ svn propedit svn:externals vendor/plugins

你可以选择使用最后发行的稳定版本:
login_engine http://svn.rails-engines.org/plugins/login_engine

或者是一个指定的版本 (recommended for releases of your code):
login_engine http://svn.rails-engines.org/logine_engine/tags/<TAGGED_RELEASE>

为了更好地运行你需要接受下面几个配置步骤。需要你修改的应用程序被列在下面:

=== 配置你的 Rails 应用程序

编辑你的 database.yml ,这是很重要的!你也可能需要设置 config/routes.rb 内的默认路由器。

=== 添加配置和启动引擎

添加下面到 environment.rb 文件的底部:

module LoginEngine
config :salt, "your-salt-here"
end

Engines.start :login

你或许应该修改 Salt 的值以让它是唯一的。你也可以用同样方式来覆写 lib/user_system.rb 文件内,其顶部的配置值。

注意:你不需要用 Engines.start :login_engine 来启动引擎,相反,如果 engine 有一个目录名 <some-name>_engine 的话,你使用 :login 来代替就可以了。

=== 添加过滤器

接着,编辑你的 app/controllers/application.rb 文件。你的 ApplicationController 文件的开始部分看起来应该是这样:

require 'login_engine' # 1

class ApplicationController < ActionController::Base
include LoginEngine # 2
helper :user # 3
model :user # 4

before_filter :login_required # 5

如果你不希望所有的动作都要求登录的话,你需要继续往下读如何用 only 限制某些动作。

添加下面到你的 ApplicationHelper 文件内:

module ApplicationHelper
include LoginEngine # 1
end

这确保在你的视图内用 user 工作的方法能正常工作。

=== 设置 ActionMailer

如果你希望在 Login Engine 内取消邮件功能,只要在你的 environment.rb 文件内简单地设置 :use_email_notification 的 config 标志为 false 就可以了:

module LoginEngine

# ... other options...
config :use_email_notification, false # 1

end

你应该注意到当邮件功能被禁止时,自动地查找丢失口令是不需要的。相反,用户提供它们的信息给系统管理员。

如果你希望使用邮件通知和账户创建确认,你必须为你的邮件设置配置 ActionMailer 。例如,你可以添加
下面到 config/environments/development.rb 文件中(对于 Mac 账户,要明确地提供用户名和口令):

ActionMailer::Base.server_settings = {
:address => "smtp.mac.com",
:port => 25,
:domain => "smtp.mac.com",
:user_name => "<your user name here>",
:password => "<your password here>",
:authentication => :login
}

You'll need to configure it properly so that email can be sent. One of the easiest ways to test your configuration is to temporarily reraise exceptions from the signup method (so that you get the actual mailer exception string). In the rescue 
statement, put a single "raise" statement in. Once you've debugged any setting problems, remove that statement to get the proper flash error handling back.


=== 创建 DB schema

在你修改完 ApplicationController 与它的帮助方法后,你可以引入 user 模型到数据库内。迁移信息在 login_engine/db/migrate/ 目录内。

你必须检查这些文件不能以任何形式出现在你的应用程序内。

你也可以添加下面行来修改表的名字

module LoginEngine

# ... other options...
config :user_table, "your_table_name"

end

... LoginEngine 配置在 environment.rb 文件内。然后到你的工程的根目录内: 

rake db:migrate:engines ENGINE=login
or(rake engine_migrate ENGINE=login)

会引入 schema 到你的数据库内。

== 包含样式表

如果你需要缺省的样式表,添加下面行到你的层中:

<%= engine_stylesheet 'login_engine' %>

... 它要出现在你的层文件的 <head> 段内。

== 整合 flash 消息到你的层 layout 中

LoginEngine 并不在包含它的视图内显示任何 flash 消息,所以你必须自己显示它们。这允许你整合任何消息到你的现有层文件内。LoginEngine 支持标准的 flash 用法:

* :warning - 警告 (失败) 消息。
* :notice - 成功消息
* :message - 通常的 (提示,信息) 消息。

这可让你更灵活地,分别安排不同的消息类。在你的层文件中,你应该检查并显示 flash[:warning], 
flash[:notice] 和 flash[:message]。例如:

<% for name in [:notice, :warning, :message] %>
<% if flash[name] %>
<%= "<div id="#{name}">#{flash[name]}</div>" %>
<% end %>
<% end %>

此外,你可以查阅 flash 帮助插件 (https://opensvn.csie.org/traccgi/
flash_helper_plugin/trac.cgi/),它支持同样的命名约定。
(my4java:在例子中是把此段放在login.rhtml内。)

= 如何使用 Login Engine 

现在你可以添加 "before_filter :login_required" 到你想保护的控制器内。

在整合登录系统到你的 Rails 应用程序之前,先导航到你新的控制器的 singup 方法。
那里你可以创建一个新的账户。在做此事之前,你最好检查一下数据库。
After integrating the login system with your rails application 
navigate to your new controller's signup method. There you can create a new account. After you are done you should have a look at your DB. Your freshly created user will be there but the password will be a sha1 hashed 40 digit mess. I find this should be the minimum of security which every page offering login & password should give its customers. Now you can move to one of those controllers which you protected with the before_filter :login_required snippet. You will automatically be re-directed to your freshly created login controller and you are asked for a password. After entering valid account data you will be taken back to the controller which you requested earlier. Simple huh?

=== 使用 before_filter 的保护

添加行 before_filter :login_required 到你的 app/controllers/application.rb 文件内,它将保护你应用程序中每个控制器内的所有方法。如果你只想控制对特定控制器的访问,从 application.rb 文件内移除此行,再将它添加到你想保护的控制器内。

在每个控制器内,你可以约束哪个方法在执行前需要过滤:

before_filter :login_required, :only => [:myaccount, :changepassword]
before_filter :login_required, :except => [:index]

=== 使用 protect?() 的保护

做为选择,你可以忽略全局 application.rb 文件内的 before_filter ,而通过在指定控制器内定义一个 protect?() 方法来约束要控制的动作。

例如,在 UserController 内我们希望允许每个人访问 'login','singup' 和 'forgot_password' 方法(否则的话,没有人能访问我们的站点)。所以可以像下面一样在 user_controller.rb 内定义一个 protect?() 方法:

def protect?(action)
if ['login', 'signup', 'forgot_password'].include?(action)
return false
else
return true
end
end

当然,你可以在你的应用程序中覆写 Engine 行为 -- 参阅下面。

== 配置

下面的配置变量在 lib/login_engine.rb 文件内设置。如果你希望覆写它们,你应该在调用 Engines.start 之前设置它们。

例如,下面可以出现在 /config/environment.rb 文件的底部:

module LoginEngine
config :salt, 'my salt'
config :app_name, 'My Great App'
config :app_url, 'http://www.wow-great-domain.com'
end

Engines.start

=== 配置选项

email_from:: The email from which registration/administration emails will appear to 
come from. Defaults to 'webmaster@your.company'.
+admin_email+:: The email address users are prompted to contact if passwords cannot
be emailed. Defaults to 'webmaster@your.company'.
+app_url+:: The URL of the site sent to users for signup/forgotten passwords, etc.
Defaults to 'http://localhost:3000/'.
+app_name+:: The application title used in emails. Defaults to 'TestApp'.
+mail_charset+:: The charset used in emails. Defaults to 'utf-8'.
+security_token_life_hours+:: The life span of security tokens, in hours. If a security
token is older than this when it is used to try and authenticate
a user, it will be discarded. In other words, the amount of time
new users have between signing up and clicking the link they
are sent. Defaults to 24 hours.
+two_column_input+:: If true, forms created with the UserHelper#form_input method will
use a two-column table. Defaults to true.
+changeable_fields+:: An array of fields within the user model which the user
is allowed to edit. The Salted Hash Login generator documentation
states that you should NOT include the email field in this
array, although I am not sure why. Defaults to +[ 'firstname', 'lastname' ]+.
+delayed_delete+:: Set to true to allow delayed deletes (i.e., delete of record
doesn't happen immediately after user selects delete account,
but rather after some expiration of time to allow this action
to be reverted). Defaults to false.
+delayed_delete_days+:: The time delay used for the 'delayed_delete' feature. Defaults to
7 days.
+user_table+:: The table to store User objects in. Defaults to "users" (or "user" if
ActiveRecord pluralization is disabled).
+use_email_notification+:: If false, no emails will be sent to the user. As a consequence,
users who signup are immediately verified, and they cannot request
forgotten passwords. Defaults to true.
+confirm_account+:: An overriding flag to control whether or not user accounts must be
verified by email. This overrides the +user_email_notification+ flag.
Defaults to true.

== 覆写控制器和视图

大多数情况下标准的 home 页并不是你想呈现给你的用户的页面。因为这个登录系统是个 Rails 引擎,覆写缺省行为并不太简单。为 home 动作修改要显示的 RHTML 模板,简单地在 RAILS_ROOT/app/views/user/home.rhtml 内创建个文件(你或许同时需要创建目录 user )。这个新的视图文件将代替登录引擎中的哪个来被使用。


== Tips & Tricks

我如何...

... 访问当前登录的用户?

A: 你可以使用 session[:user] 来获得 user 对象。
例如:
Welcome <%= session[:user].name %>

你也可以使用由 UserHelper 提供的 'current_user' 方法:
例如:
Welcome <%= current_user.name %>


... 只对少数几个方法进行约束? 

A: 在范围内绑定使用 before_filters 。 
例如: 
before_filter :login_required, :only => [:myaccount, :changepassword]
before_filter :login_required, :except => [:index]

... 在视图内检查用户是否登录?

A: session[:user] 会话会告诉你。这个有个帮助方法的例子,你也可以让它做更多的事。
例如: 
def user?
!session[:user].nil?
end

... 如何返回用户登录前输入的 URL ?

A: 名为 "store_location" 的方法会把用户送回到它在登录前请求的页面。
例如:
在登录前用户输入 /articles/show/1 。在 articles_controller.rb 
内,添加 store_location 给 show 方法并发送用户到登录表单。在登录后,
会弹回 /articles/show/1 的日志。

你可以在 http://wiki.rubyonrails.com/rails/show/SaltedLoginGenerator 
中找到更多的帮助方法。

== Troubleshooting

One of the more common problems people have seen is that after verifying an account by following the emailed URL, they are unable to login via the normal login method since the verified field is not properly set in the user model's row in the DB.

The most common cause of this problem is that the DB and session get out of sync. In particular, it always happens for me after recreating the DB if I have run the server previously. To fix the problem, remove the /tmp/ruby* session files (from wherever they are for 
回到帖子顶部

回帖 引用 2楼[楼主] CMO涔漠

用户形象图片



[Rails 常用插件简介]atom_feed_helper


前两天(好像?)看到大家在讨论feeds生成,工作累了,来写点文字,稍作休息一下:)

DHH写的,很小巧实用的代码

0: 前因
cclong 的帖子:如何制作feed?
http://www.ruby-lang.org.cn/foru ... &extra=page%3D1

1:安装

[Copy to clipboard] [ - ]CODE:
ruby script/plugin install atom_feed_helper

2:使用
这个插件太简单的,没什么好说的,大家如果有什么问题请跟帖,一起讨论。(下面代码取之插件中的README). 大家一起来阅读一下代码
Controller file:posts_controller.rb

[Copy to clipboard] [ - ]CODE:
      def index
        @posts = Post.find(:all, :limit => 25)
       
        respond_to do |format|
          format.html
          format.atom
        end
      end

View file:posts/index.atom

[Copy to clipboard] [ - ]CODE:
      atom_feed(:url => formatted_people_url(:atom)) do |feed|
        feed.title("Address book")
        feed.updated(@people.first ? @people.first.created_at : Time.now.utc)
     
        for post in @posts
          feed.entry(post) do |entry|
            entry.title(post.title)
            entry.content(post.body, :type => 'html')
    
            entry.author do |author|
              author.name(post.creator.name)
              author.email(post.creator.email_address)
            end
          end
        end
      end

生成,这个也就是你想要的:

[Copy to clipboard] [ - ]CODE:
<?xml version="1.0" encoding="UTF-8"?>
  <feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
    <id>tag:localhost:people</id>
    <link type="application/atom+xml" rel="self" href="http://example.com/people.atom"/>
    <title>Address book</title>
    <updated></updated>
    <entry>
      <id>tag:localhost:3000,2007-05-18T16:35:00-07:00:Person1</id>
      <published>2007-05-18T16:35:00-07:00</published>
      <link type="text/html" rel="alternate" href="http://example.com/people/1" />
      <title>The future is now</title>
      <content type="html">Once upon a time</content>
      <author>
        <name>DHH</name>
        <email>david@loudthinking.com</email>
      </author>
    </entry>
    <entry>
      <id>tag:localhost:3000,2007-05-18T09:36:00-07:00:Person2</id>
      <published>2007-05-18T09:36:00-07:00</published>
      <link type="text/html" rel="alternate" href="http://example.com/people/1" />
      <title>Matz</title>
      <content type="html">This is Matz</content>
      <author>
        <name>Matz</name>
        <email>Matz</email>
      </author>
    </entry>
  </feed>

三:源码
/plugins/atom_feed_helper/lib/atom_feed_helper.rb
http://dev.rubyonrails.org/brows ... atom_feed_helper.rb

[Copy to clipboard] [ - ]CODE:
module AtomFeedHelper
  def atom_feed(options = {}, &block)
    xml = options[:xml] || eval("xml", block.binding)
    xml.instruct!

    xml.feed "xml:lang" => "en-US", "xmlns" => 'http://www.w3.org/2005/Atom' do
      xml.id("tag:#{request.host},2007:#{request.request_uri.split(".")[0].gsub("/", "")}")
      
      if options[:root_url] || respond_to?(:root_url)
        xml.link(:rel => 'alternate', :type => 'text/html', :href => options[:root_url] || root_url)
      end

      if options[:url]
        xml.link(:rel => 'self', :type => 'application/atom+xml', :href => options[:url])
      end

      yield AtomFeedBuilder.new(xml, self)
    end
  end


  protected
    class AtomFeedBuilder
      def initialize(xml, view)
        @xml, @view = xml, view
      end

      def entry(record)
        @xml.entry do 
          @xml.id("tag:#{@view.request.host_with_port},2007:#{record.class}#{record.id}")
          @xml.published(record.created_at.xmlschema) if record.respond_to?(:created_at)
          @xml.updated(record.updated_at.xmlschema) if record.respond_to?(:updated_at)

          yield @xml

          @xml.link(:rel => 'alternate', :type => 'text/html', :href => @view.polymorphic_url(record))
        end
      end

      private
        def method_missing(method, *arguments, &block)
          @xml.__send__(method, *arguments, &block)
        end
    end
end

Rails的“契约”中有一条,DRY:Don't repeat yourself,还记得么?
回到帖子顶部
个人信息
  • 荣誉+3
  • 荣誉+2
  • 荣誉+1
  • 荣誉-1
  • 荣誉-2
  • 荣誉-3
发表留言
  • 文章不错!
  • 精华好文!
  • 支持原创文章!
  • 帖子图文并茂,好!
  • 真知灼见,说得好!
  • 恶意广告
  • 违规内容
  • 严重灌水
  • 重复发帖
  • 标题党
你确定要删除此楼层吗
扣20点经验值

快速回复进入高级回复

插入图片 选择表情

验证码 看不清?换一张(不区分大小写)

[完成后按Ctrl+Enter发表]
[回复须知]