Rails

导读:

   关键字: Rails Smart Pluralization

  对英文网站,我们常常需要显示一个名词的复数形式。

  而Rails就提供了一个称为Inflector的工具来计算该逻辑,并且ActionView有一个wrapper方法来处理常见的复数形式,如:

   代码

  There are <%= pluralize @recipes.size, "recipe" %>.

  当你的网站不是使用English或者有一些比较特殊的复数规则时,我们可以在config/environment.rb里定义这些规则,如:

   代码

  Inflector.inflections do |inflect| inflect.plural /^(ox)$/i, '/1en' inflect.singular /^(ox)en/i, '/1' inflect.irregular 'person', 'people' inflect.uncountable %w( fish sheep ) end

  19:29 | 永久链接 | 浏览 (211) | 评论 (0) | Ruby |

   关键字: Rails Use Ajax to Trim Fast, Static Pages

  今天让我们看看怎样使用Rails和Ajax得到静态页面。

  看下面这个页面:

   代码

  
  • < li> < div id="product-1" class="product-overview"> < span class="title">Learn to Program (Chris Pine) <%= link_to_remote "detail", :update => 'product-1-detail', :method => 'get', :url => '/catalog/details/1.html' %> < div id='product-1-detail'>


  这里link_to_remote生成一个detail链接,用户点击它时,就会取得1.html并替换id为product-1-detail的div的content。默认method为post,我们取静态内容所以改为get。

  17:57 | 永久链接 | 浏览 (235) | 评论 (0) | Ruby |

   关键字: Rails Cheap and Easy Theme Support

  你可能需要给你的站点用户添加一个主题样式支持。

  让我们看看用Rails实现该功能是多简单。

  1,给User模型添加类型为string的style字段

  2,修改app/views/layouts/application.rhtml

   代码

  < head> <%= stylesheet_link_tag(session[:user].style || "default") %> < body> < div id='main'> < div id='header'> < h1>Welcome, <%= session[:user].name %>! < div id='content'> <%= yield %>

  这样没有配置主题样式的用户将默认使用default.css,而User.style为"hideous"的用户将使用public/stylesheets/hideous.css

  17:30 | 永久链接 | 浏览 (240) | 评论 (0) | Ruby |

   关键字: Rails Live Search

  这次我们看看Rails里text_field的auto_complete,即Live Search。

  1,添加Recipe的Migration

   代码

  class AddRecipes   2,添加SearchController

   代码

  class SearchController
  这里的auto_complete_for :recipe, :name会告诉Rails自动生成一个auto_complete_for_recipe_name()方法,它将搜索匹配输入的文本的对象并渲染结果。

  3,添加search.rhtml

   代码

  < head>="" :defaults="" search="" recipes
  text_field_with_auto_complete这个Helper方法会在页面生成一些HTML和JavaScript,从而使得recipe的name域自动搜索和补全。

  向数据库加几条数据并访问http://localhost:3000/search/search看看效果吧!

  如此简洁的几行代码就为我们添加Live Search功能,何乐而不为呢?

  最后更新: 2007-04-23 17:41

  17:09 | 永久链接 | 浏览 (219) | 评论 (0) | Ruby |

   关键字: Rails Live Preview

  像蛙眼等有时候需要给用户提供预览查看,今天我们就来看看利用Rails和Prototype快捷的提供Live Preview功能。

  1,在layout里加入prototype.js

  如app/views/layouts/standard.rhtml:

   代码

  < head> <%= javascript_include_tag "prototype" %> < body> <%= yield %>

  2,定义Entry类

  如app/models/entry.rb:

   代码

  class Entry attr_accessor :title, :body end

  我们的demo中的模型没有继承ActiveRecord::Base类,只是简单的提供两个可访问的字段

  3,定义controller

  如app/controllers/diary_controller.rb:

   代码

  class DiaryController false end end

  4,定义rhtml模板

  app/views/diary/new.rhtml:

   代码

  <%= start_form_tag({:action =>"save"}, :id => "entry-form")%> Title:<%= text_field :entry, :title %>
Content:<%= text_field :entry, :body %>
<%= submit_tag "Save" %><%= end_form_tag %><%= observe_form "entry-form", :frequency => 1, :update => "live-preview", :complete => "Element.show('live-preview')", :url => {:action => "preview"} %>< div id="live-preview" style="display: none; border: 1px solid">

  app/views/diary/preview.rhtml:

   代码

  

Diary entry preview

< h3><%= params[:entry][:title]%><%= textilize params[:entry][:body] %>

  5,打完收工

  访问http://localhost:3000/diary/new即可看到Live Preview效果

  16:28 | 永久链接 | 浏览 (228) | 评论 (0) | Ruby |

   关键字: Rails Lightning-Fast JavaScript Auto-completion

  Gmail中你输入收信人地址时会自动搜索并提示,速度很快,因为Gmail不是每次都从后台搜索,而是一开始就

  把地址加载到页面中,然后在页面中匹配并搜索。让我们看看怎样在Rails里实现它。

  1,准备搜索数据

  我们创建app/controllers/book_controller.rb:

   代码

  class BookController false end end

  这里我们设置headers的content-type为text/javascriipt。

  2,封装JavaScript数据

  我们创建返回的页面app/views/book/authors_for_lookup.rhtml:

   代码

  var authors = new Array(<%= @authors.size%>);<% @authors.each_with_index do |author, index|%> authors[<%= index %>] = "<%= author.name %>";<% end %>

  我们在该rhtml中直接写javascript代码,并用Ruby代码动态取得和填充authors数据

  3,写搜索页面

  如app/views/book/search_page.rhtml:

   代码

  < head> <%= javascript_include_tag :defaults %> < script src="/book/authors_for_lookup" type="text/javascript"> < style> div.auto_complete { width: 350px; background: #fff; } div.auto_complete ul { border: 1px solid #888; margin: 0; padding: 0; width: 100%; list-style-type: none; } div.auto_complete ul li.selected { background-color: #ffb; } div.auto_complete ul strong.highlight { color: #800; margin: 0; padding: 0; } < body> < label for="author_lookup">Author Search < input type="text" id="author_lookup" name="author_lookup" /> < div class="auto_complete" id="author_lookup_auto_complete"> <%= javascript_tag("new Autocompleter.Local('author_lookup', 'author_lookup_auto_complete', authors, {fullSearch: true, frequency: 0, minChars: 1, } );") %>

  Autocompleter.Local在本地(当前页面中)取数据,让我们访问http://localhost:3000/book/search_page看看效果,很不错哦!

  最后更新: 2007-04-23 14:46

  00:33 | 永久链接 | 浏览 (301) | 评论 (0) | Ruby |

   关键字: Rails Beast

  Beastis a small, light-weight forum in Rails with a scary name and a goal of around 500 lines of code when we're done.

  Getting Started with Beast:

  1,下载源码

   代码

  svn co http://svn.techno-weenie.net/projects/beast/trunk beast

  2,安装RedCloth

   代码

  sudo gem install RedCloth

  3,配置数据库

  编辑database.yml

  4,生成数据库表

   代码

  rake db:schema:load RAILS_ENV=production

  可以了,跑起来试试。

  第一个注册的用户为Admin。

  最后更新: 2007-04-20 14:39

  14:37 | 永久链接 | 浏览 (599) | 评论 (0) | Ruby |

   关键字: Rails RJS

  本来题目应该为Update Multiple Page Elements With One Ajax Request,但蛙眼的博客标题字数有限,遂更名为RJS,因为这次主要了解的就是Rails的RJS。

  让我们看看一个RJS的例子,通过一次Ajax请求灵活的更新页面中的多个元素。

  1,新建Rails项目和一个rhtml

  如app/views/ajax_fun/index.rhtml:

   代码

  < head> <%= javascript_include_tag :defaults %> < body> < h2 id="header">AjaxFun < div> This page was initially loaded at <%= Time.now %> < div> This page was updated at <%= Time.now%> < ul id="the_list"> < li>Initially, the first item < li>Another item < li id="item_to_remove">This one will be removed. < div id="initially_hidden" style="display: none;"> This text starts out hidden. <%= link_to_remote "Ajax Magic", :url => {:action => "change"} %>


  该页面作为Ajax调用的基本页面,我们用javascript_include_tag引入了Rails自带的JavaScript

  注意link_to_remote这个helper方法,它的:url表明我们将用Prototype的Ajax.Request(...)方法调用服务器端的change方法。

  2,创建一个controller

  如app/controllers/ajax_fun_controller.rb:

   代码

  class AjaxFunController   3,创建一个RJS模板

  因为我们对controller的change方法做RJS,所以我们的RJS模板为app/views/ajax_fun/change.rjs:

   代码

  page['time_updated'].replace_html Time.now page[:time_updated].visual_effect :shake page.insert_html :top, 'the_list', '
  • king of="" the="" hill
      4,看看效果

      打开浏览器访问http://localhost:3000/ajax_fun,点击Ajax Magic链接即可。

      我们的change.rjs更新了time_updated的时间,并有一个shake的effect,然后在the_list的顶端插入一行,并highlight它,然后我们显示了initially_hidden这个隐藏div,然后我们在page load成功3秒后alert我们的Rails的版本,最后删除item_to_remove这行。

      13:00 | 永久链接 | 浏览 (471) | 评论 (2) | Ruby |

      关键字: Rails Creating a Drag-and-Drop Sortable List

      今天来看看用Rails创建一个可拖拽的List。

      1,创建Rails项目,搭建数据库

      代码

      Migration: class AddPersonAndGroceryListsAndFoodItemsTables :position belongs_to :person end class FoodItem :grocery_list end

      这里一个Person对应多个GroceryList,一个GroceryList对应多个FoodItem

      我们可以运行 ruby script/console或者直接访问数据库来初始化几条数据

      这里我们创建一个Person,一个GroceryList和3个FoodItem,并保持外键关联

      2,引入javascript

      可以通过用一个layout文件来做这件事,如app/views/layouts/standard.rhtml:

       代码

      < head> <%= javascript_include_tag :defaults %> < body> <%= yield %>

      3,创建一个列表controller

      如app/controllers/grocery_list_controller.rb:

       代码

      class GroceryListController true end end

      4,创建列表视图

      如app/views/grocery_list/show.rhtml:

       代码

      

    <%= @grocery_list.person.name %>'s Grocery List

    < h3><%= @grocery_list.name %>< ul id="grocery-list"> <% @grocery_list.food_items.each do |food_item| %> < li id="item_<%= food_item.id %>"> <%= food_item.quantity %> units of <%= food_item.name %>
  • <% end %><%= sortable_element 'grocery-list', :url => { :action => "sort", :id => @grocery_list }, :complete => visual_effect(:highlight, 'grocery-list')%>

      5,访问看看效果

      打开浏览器访问http://localhost:3000/grocery_list/show/1看看

      我们拖拽一条数据在列表中的位置,然后刷新页面,发现该条数据的位置在数据库中保存了

      6,原理

      我们的FoodItem类有一个position列,并且声明为acts_as_list,并且GroceryList按照position来排序,我们的sortable_element()这个helper方法为我们生成一段为Sortable.create(...)的JavaScript代码为我们做Ajax调用,访问sort方法,而sort方法则在数据库中保存列表经拖拽后的新的position。

      00:53 | 永久链接 | 浏览 (357) | 评论 (0) | Ruby |

       关键字: Rails Making Your Own JavaScript Helper

      上次我们在每天一剂Rails良药之In-Place Form Editing里讲到In-Place编辑,大家意犹未尽吧!

      但是现在只能支持text和textarea的In-Place Edit,如何添加一个对select的In-Place Edit呢?

      或者说,我们怎样写自己的JavaScript Helper插件呢?

      今天我们就在上篇文章的基础上写一个对Rails自带In-Place Editor的扩展,让它支持对select的In-Place Edit,并且了解一下如何写我们自己的JavaScript Helper。

      1,了解Rails自带的InPlaceEditor并写我们自己的InPlaceSelectEditor

      Rails自带的InPlaceEditor在文件public/javascripts/controls.js里定义,它绑定click事件到enterEditMode()方法,该方法调用createForm()和createEditField(),这两个方法主要就是生成form和text/textarea,现在我们的思路就是继承InPlaceEditor并重写createEditField()方法,让它生成select。

      创建public/javascripts/in_place_select_editor.js文件:

       代码

      Ajax.InPlaceSelectEditor = Class.create(); Object.extend(Object.extend(Ajax.InPlaceSelectEditor.prototype, Ajax.InPlaceEditor.prototype), { createEditField: function() { var text; if(this.options.loadTextURL) { text = this.options.loadingText; } else { text = this.getText(); } this.options.textarea = false; var selectField = document.createElement("select"); selectField.name = "value"; selectField.innerHTML = this.options.selectOptionsHTML || "< option>" + text + ""; $A(selectField.options).each(function(opt, index) { if(text == opt.value) { selectField.selectedIndex = index; } } ); selectField.style.backgroundColor = this.options.highlightcolor; this.editField = selectField; if(this.options.loadTextURL) { this.loadExternalText(); } this.form.appendChild(this.editField); } });

      可以看到,我们继承了InPlaceEditor,并覆盖了它的createEditField()方法并生成一个selectField。

      2,在我们的页面中include我们的JavaScript

      我们通过在app/views/layouts/contacts.rhtml中引入我们刚才的JavaScript文件来让它全局生效:

       代码

      <%= javascript_include_tag "in_place_select_editor" %>

      3,写个demo页测试一下我们的JavaScript

      创建一个app/views/contacts/demo.rhtml:

       代码

       Some Value< script type="text/javascript"> new Ajax.InPlaceSelectEditor( 'an_element_we_want_to_edit', '/an/update/url', { selectOptionsHTML: '
  • ' + '
  • ' + '
  • '});

      现在让我们访问一下http://localhost:3000/contacts/demo看看,是不是有In Place Select效果了?

      别急,我们再写一个helper来让我们在view里用的更爽,而不用每次手动调用Ajax.InPlaceSelectEditor()。

      4,写一个helper来包装我们的JavaScript

      在app/helpers/application_helper.rb文件里添加以下两个方法:

       代码

      def in_place_select_editor_field(object, method, tag_options = {}, in_place_editor_options = {}) tag = ::ActionView::Helpers::InstanceTag.new(object, method, self) tag_options = { :tag => "span", :id => "#{object}_#{method}_#{tag.object.id}_in_place_editor", :class => "in_pace_editor_field"}.merge!(tag_options) in_place_editor_options[:url] = in_place_editor_options[:url] || url_for({ :action => "set_#{object}_#{method}", :id => tag.object.id }) tag.to_content_tag(tag_options.delete(:tag), tag_options) + in_place_select_editor(tag_options[:id], in_place_editor_options) end def in_place_select_editor(field_id, options = {}) function = "new Ajax.InPlaceSelectEditor(" function <<"'#{field_id}', " function <<"'#{url_for(options[:url])}'" function <<(', ' + options_for_javascript({'selectOptionsHTML' => %('#{escape_javascript(options[:select_options].gsub(//n/, ""))}')})) if options[:select_options] function <<')' javascript_tag(function) end

      这样我们就可以用helper方法来在view里生成JavaScript方法了

      5,测试一下我们的In Place Select Editor吧

      编辑app/views/contacts/show.rhtml:

       代码

      

    < b>name=""
    country:

    < br/><%= link_to 'Back', :action => 'list' %>

      这里我们的:select_options => country_options_for_select用到了Rails内建的country_options_for_select()这个helper方法。

      好了,New一个Contact,并点击进入Show页面,看看我们的In Place Select Editor的效果吧!



    本文转自

    http://hideto.javaeye.com/category/7643?list=1&page=26

    <>king>
<>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值