??xml version="1.0" encoding="utf-8" standalone="yes"?>
效果和xiaonei?nbsp; 更多新鲜?nbsp; 一P
前面有篇文章也介l了一个像 twitter more 的方式分늚ҎQ不q那个是?protorype 做的。。那个做h单一点,因ؓrailsl我们封装了 insert_html ?link_to_remote {方法,q样更加便捷Q但是解决jquery ?prototype的confilct是一件很让h头疼的事Q烦性今天又实现了一个基?jquery 的方?环境是在rails中,需要?will_paginate 插gQ?br />Demo:
view:
<script>
(function($){
var settings;
$.bottomlessPagination = function(callerSettings) {
settings = $.extend({
ajaxLoaderPath:'/images/loading.gif',
results:'.results', // results q回l果外部的class
objName:'',
callback:null
},callerSettings||{});
settings.imgLoader = new Image();
settings.imgLoader.src = settings.ajaxLoaderPath;
settings.href = $(".current").next().attr("href"); //current ?will_paginate 默认的当前页 href 的名?br />
if ($('div.pagination').size() > 0){ // pagination ?will_paginate 默认?class
$('div.pagination').wrap("<div class='pagination_links'></div>").hide();
$('.pagination_links').append(
"<div class='live_pagination'>" +
"<a class='more_links' style='cursor:pointer;'> 查看 " + settings.objName + "...</a>" +
"</div>"
);
}
$(".more_links").click(function(){
$(".live_pagination").hide();
if ($(".now_loading").size() == 0)
$(".more_links").after("<img class='now_loading' src='"+settings.imgLoader.src+"' />");
else
$(".now_loading").show();
$.get(
settings.href,'',function(data){
$(settings.results).addrows(data);
$(".now_loading").hide();
$(".live_pagination").show();
}
);
return false;
});
$.fn.addrows = function(data) {
//remove live pagination if there are no more results
// alert(data.length);
if (data.length === 1 ){
// alert(data.length);
$('.live_pagination').remove();
$('.pagination_links').append(
"<div class='no_pagination'>" +
"没有" + settings.objName +
"</div>"
);
return false;
}
//change the href
ind=settings.href.indexOf("page=");
page=parseInt(settings.href.charAt(ind+5))+1;
start=settings.href.slice(0,ind+5);
stop=settings.href.slice(ind+6);
settings.href=start.concat(page.toString()).concat(stop);
//add results to the page
$(settings.results).append(data);
if (settings.callback) settings.callback();
};
};
})(jQuery);
</script>
<div class="results">
<%= render :partial => 'activity' , :collection => @all_feed %>
</div>
<%= will_paginate @all_feed ,
:class => 'pagination',
:previous_label => '« Previous',
:next_label => 'Next »',
:renderer => 'WillPaginate::LinkRenderer' %>
<div>
<div class="now_loading" style="display:none;">
<img src="http://www.aygfsteel.com/images/loading.gif"></img>
</div>
<script>
$.bottomlessPagination({objName:'更多更新', callback:function(){
//highlight current row
// $("div.results").effect("highlight", {}, 3000);
}});
</script>
Action:
def index
if request.xhr?
sleep(1) # make request a little bit slower to see loader :-)
render :partial => 'activity' , :collection => @all_feed
end
partial:_activity.html.erb
partial 里输出数据即?br />
主要的注意点是注意对应class 不要写错了,同样Q你也可以把class 换位id做,jquery取idpP $("#ID")
上面js文g下蝲Q?br />http://www.dbank.com/download.action?k=3094283bf64e445f9530ac0554ebc9ce
ref:
http://github.com/davidwparker/jquery-bottomless-pagination
]]>
前面的配|一?br />
Demo:
1,安装 chronic
gem install chronic
2,安装插g
ruby script/plugin install svn://rubyforge.org/var/svn/fauna/ultrasphinx/trunk
q个是网上提供的ҎQ目前似乎找不到q个源了。。徏议直接从github download 下蝲
http://github.com/fauna/ultrasphinx
3Q安装完Ultrasphinx之后Q将Q?
vendor/plugins/ultrasphinx/examples/default.base
复制刎ͼ
config/ultrasphinx/default.base
其中的Q?
charset_type = utf-8
改ؓQ?
charset_type = zh_cn.utf-8
q且在charset_type讄的下面加入一行:
charset_dictpath = /home/feng/RailsProject/Search/lib Q?你uni.lib 字典所在的路径
然后删除所有charset_table的设|?
4QModel
is_indexed :fields => ['created_at', 'name']
is_indexed :fields => ['created_at', 'content']
5Qaction
def index
# thinking_sphinx
# @articles = Article.search params[:search], :include => :author, :match_mode => :boolean
#ultrasphinx
@search = Ultrasphinx::Search.new(:query => params[:search])
@search.run
@articles = @search.results
end
6,生成配置文gQ?
rake ultrasphinx:configure
在config/ultrasphinx下创Z一个development.confQ这个文件就是Sphinx的配|文件?
7,创徏索引Q?
rake ultrasphinx:index
索引创徏在了 default.base 中你定义的path 路径?br />
8Q?启动Sphinx的searchd服务Q?
rake ultrasphinx:daemon:start
对应的停止是 rake ultrasphinx:daemon:stop
9,启动webrick
ok了。。?br />目下蝲Q?br />http://www.uushare.com/user/fl1429/file/2043752
ref:
http://www.javaeye.com/topic/200065?page=1
http://github.com/fauna/ultrasphinx
]]>
效果预览Q?br />
1Q?http://www.zikii.com/ q个|站 也是Z sphinx 实现?br />
2Q我?br />
׃目需要,需要实现站内搜索,全文索和 中文分词 功能Q最后选型?sphinx + libmmseg + thinking_sphinx Q?折腾了好大一会,最后测试成?br />
sphinx 是俄国h开发的opensourse 搜烦引擎Q烦引速度很快Q?libmmseg 是中国h开发的中文分词E序Qthinking_sphinx 是封装调用sphinx的rails plugin
下面用到的所有资?打包下蝲Q?br />
http://www.uushare.com/user/fl1429/file/2043579
1Q项目的所有的源码~译安装 Q?全部Ud /root 下进?凡是出现权限不够的, 在命令前加上 sudo
2Q安?libmmseg
./configure
make
make install
具体可以参考:
http://www.coreseek.cn/opensource/mmseg/
3,安装 ruby 扩展Q进?mmseg ruby 目录?Q注意最后面有一个点Q?br />
cd ruby
cp /usr/local/include/mmseg/*.h .
cp ../src/*.h .
cp ../src/css/*.h .
ruby extconf.lin.rb
make
sudo make install
成功的话Q可以到irb下,试看看是否成功?br />
irb
require 'mmseg'
注意:如果在这一步出?且出错提CZؓQ?br />
css/UnigramCorpusReader.cpp:89: error: ’strncmp’ was not declared in this scope
则需手工~辑.src/css目录下UnigramCorpusReader.cpp 文g,在其W一行加?br />
#include <string.h>
然后重新 make,卛_通过
4Q创典文?br />
q入 mmseg ?data 目录?br />
mmseg -u unigram.txt
把生成的文g名改?uni.lib
5,安装sphinx (把两个补丁放?解压??sphinx?
cd sphinx-0.9.8-rc2
patch -p1 < sphinx-0.98rc2.zhcn-support.patch Qpatch中文补丁
patch -p1 < fix-crash-in-excerpts.patch # patch 防crash 补丁
Copy mmseg安装文g夹下 src/csr_typedefs.h ?br />
src/css/SegmenterManager.h 到Sphinx安装文g夹下?src
文g夹下
./configure
make
sudo make install
注意Q如果在q一步出?br />
/usr/local/include/mmseg/freelist.h:22: error: ‘strlen’ was not declared in this scope
的错误,手工修改 /usr/local/mmseg/include/mmseg/freelist.h
在上面添?br />
#include <string.h>
以上的配|?sphinx 支?中文分词 搜烦了。。?br />
Demo:
1,依照 Ryan 的例?配置 好基本的英文搜烦
http://railscasts.com/episodes/120-thinking-sphinx
2Q重Ҏ model 里的 定义索引
define_index do
indexes content
indexes :name, :sortable => true
indexes comments.content, :as => :comment_content
indexes [author.first_name, author.last_name], :as => :author_name
has author_id, created_at
end
3Q把上面生成?uni.lib 辞典文g 拷入 目?lib ?Q或者别的地方,看你配置里的charset_dictpath?不编译的话,可以用别人现成的uni.libQ?br />
4Q在目?config 下新Z?sphinx.yml 文g
development: &my_settings
enable_star: 1
min_prefix_len: 0
min_infix_len: 2
min_word_len: 1
max_results: 70000
morphology: none
listen: localhost:3312
charset_dictpath: /home/feng/RailsProject/Search/lib
test:
<<: *my_settings
production:
<<: *my_settings
上面?br />
/home/feng/RailsProject/Search/lib 可以写成 "#{RAILS_ROOT}/lib"
5Q生成配|文?br />
rake ts:config
q样config 下会生成一?development.sphinx.conf 文g
扑ֈ charset_type = utf-8 把后?utf-8 修改?zh_cn.utf-8,q在下面d如下语句
charset_dictpath = /home/feng/RailsProject/Search/lib Q你工程的lib路径Q?br />
6Q徏立烦?br />
rake ts:index INDEX_ONLY=true
注意后面必须d INDEX_ONLY=true不然的话Q配|文件会被重|?q有不要写成 INDEX_ONLY = true
7Q启动sphinx服务
rake ts:start
8,启动webrick
注意Qsphinx 必须在webrick的前?先启?br />
我的demo目Q其实就是上面ryan 的,下蝲后可以看到我的具体配|,或者详l的内容
http://www.uushare.com/user/fl1429/file/2043752
ref:
http://wiki.github.com/cogentsoft/zbs/180787
http://www.javaeye.com/topic/431217?page=1
http://www.javaeye.com/topic/196451
http://blog.sina.com.cn/s/blog_412d58ec010090pq.html
http://freelancing-god.github.com/ts/en/rake_tasks.html
]]>
效果Q?br />http://www.dzone.com/links/index.html
http://flexidev.co.za/projects/jqpageflow/
http://paperc.de/documents
像上面的三个|站 的分|?是 scrolling pagination , 或??pageless pagination , endless pagination 用这些作为关键字Q?都会搜到很多的demoQ?q里我介l?一U?demoQ开?环境 ?rails Qof course , 你也可以在其他的q_使用。?br />
最?一直在用各U?分页的效果,一般都?ajax的, 例如前面 有介l了 prototype pagenation like twitter more button, q有 jquery ajax pagenation,q里又是 jquery scrolling pagination.....
Demo:
依赖?
will_paginate 插g
jquery.js
jquery.pageless.js
请到 下面?那个 ref link 里下
Action:
def show
@client_info = ClientInfo.find(params[:id])
@comments = @client_info.comments.paginate(:per_page => 5 , :page => params[:page])
if request.xhr?
sleep(2) # make request a little bit slower to see loader :-)
render :partial => 'comment' , :collection => @comments #q回 数据的partial
end
end
解释 Q?server ?br />
helper method :
# scrolling paginate like greader
def pageless(total_pages, url=nil)
opts = {
:totalPages => total_pages,
:url => url
#:loaderMsg => '加蝲?..'
}
javascript_tag("$('#ajaxcomments').pageless(#{opts.to_json});")
end
解释; 装了一?pageless ҎQ即实现 scrolling load 的的Ҏ
view: show.html.erb
..............
<%= render :partial => 'wall' %>
.........................
解释 Q?前端 view
partial : _wall.html.erb
<div class="wall" id ="ajaxcomments">
<%- unless @client_info.comments.empty? -%>
<%= render :partial => 'comment', :collection => @comments %>
<%- end -%>
<%= will_paginate @comments ,
:class => 'pagination',
:previous_label => '« Previous',
:next_label => 'Next »',
:renderer => 'WillPaginate::LinkRenderer' %> <%#= pageless must use will_paginate default style %>
<%= pageless(@comments.total_pages, client_info_path(@client_info)) %>
</div>
解释 Q?注意q里需?定义 一?idQ?q有 是 will_paginate 里的那些 参数 可以 不要 的,q里我加的,是因?我的 enviroment.rb ?加了 will_paginate ?配置Q如?你没有的话, 可以L?br />partial : _comment.html.erb
..............
<%= display comment.body %>
.........................
解释 Q?昄?内容
ref :
http://github.com/jney/jquery.pageless/tree/master
]]>
anchor 说白?是 q入 q个 面的时候, 定位到页面指定的部分Q例如一个个人用L界面Q最下面是留a版,如果你采用传l的方式提交留言的话Q那么就可以使用anchor定位提交后显C的位置
使用ҎQ?br />
1,url标识
a href = ............./network#Comment
network.html.erb
<a name="Comment"></a>
只要在network.erb.html 面中加?nbsp; 上面 那句话, 加在哪里 定位显C在哪了,或?指定一?div的idgؓ Comment 卛_
2Qrails 自带?:anchor 参数
url or path :
user_path(@user,:anchor => 'Comment')
user_url(@user,:anchor => 'Comment')
上面在rails RESTful 架构的程序中 l常 可见q种路径写法Q那么你可以利用 :anchor 来标识。。?br />
]]>
记得以前文章写过 rails autocomplete 插g的用方法, 那个是基?prototype 的, qxJquery用的最多。。所以必ȝjquery 实现 Q?q样?demo |上太多。。。。下面介l在rails 中的一Usolution
需要的Q?br />
jquery.js
jquery.complete.js
jquery.autocomplete.css
demo :
View:
<script>
$(document).ready(function() {
$("#recipient").autocomplete("/myaccount/res_message", {
delay:10,
minChar: 1,
multiple: true,
parse: function(data) {
return $.map(eval(data), function(item) {
return {
data: item,
value: item.name,
result: item.name
}
});
},
formatItem: function(item) {
return item.show;
}
}).result(function(e, item)
{
$("#recipient").val(item.name);
});
});
</script>
<p><%= text_field_tag :recipient, :id => 'recipient' %></p>
解释Q?br />
#recipient 是对应的 id
/myaccount/res_message 对应h?url
item是参?br />
name ?show ?q回的变?br />
action:
def res_message
key = params[:q] if params[:q]
@result = ClientInfo.get_login_name(key, '' , 'key')
respond_to do |format|
format.js # default : res_message.js.erb
end
end
解释 params[:q] q 是默认向后台发送的关键字查?参数Q?q且默认的limit ?0 条数?br />
view:res_message.js.erb
<% if @result -%>
<% i=0 %>[
<% for result in @result %>
<% if i==0 %>
{name:"<%= result.login_name %>",show:"<%= result.login_name + " " %>" + "<%= result.sure_name.nil? ? " " : result.sure_name + " " %>"}
<% else %>
,{name:"<%= result.login_name %>",show:"<%= result.login_name + " " %>" + "<%= result.sure_name.nil? ? " " : result.sure_name + " " %>"}
<% end %>
<% i+=1 -%>
<% end -%>]
<% end -%>
解释Q?该view 是返回的数据Q返回的是一个JSON数组
具体详细的可以参考:
http://docs.jquery.com/Plugins/Autocomplete
http://view.jquery.com/trunk/plugins/autocomplete/demo/
]]>
效果预览Q?br />
一?我们 在rails ?分页 will_paginate 是必不可的插gQ但?一般都是基?prototype 的,例如 ajax 式的分页Q?通过 RemoteLinkRenderer改变 css 样式{等Q都?Zprototype 的,但是 prototype ?Jquery 在项目中 l常遇到conflict Q这??让h 头疼Qrails 装好的ajaxҎQ好?都因?jquery 不能用,jquery 那么 ?前端 用户体验Q又因ؓ prototype 出现 conflict Q??Z?怺D杀 呢。。。。?br />
上面实现的核心思想 ?前端 通过 jquery?异步调用数据Q?后台 rails 通过 respond_to fotmat.js 的方?l予 q回数据。。?br />
Demo:
layout 中导入:
<%= stylesheet_link_tag 'pagination' -%>
<%= javascript_include_tag 'jquery' %>
pagination 是改变分늚样式
Action:
def index
@products = Product.paginate(:per_page => 10, :page => params[:page])
respond_to do |format|
format.html #default : index.html.erb
format.js {:layout => false} # default : index.js.erb
end
end
View:
index.html.erb
<div id="product">
<%= render :partial => 'products' %>
</div>
index.js.erb
$("#product").html("<%= escape_javascript(render :partial => "products") %>");
escape_javascript 是{义的意??<%=h %> q里?h 差不?br />
partial :
_products.html.erb
<script>
$(function() {
$(".apple_pagination a").live("click", function() {
$(".apple_pagination").html("Page is loading...");
$.get(this.href, null, null, "script");
/* alert(this.href); */
return false;
});
});
</script>
<%= will_paginate @products , :class => 'apple_pagination' ,:previous_label => '<<上一?, :next_label => '下一?gt;>' :renderer => 'WillPaginate::LinkRenderer' %>
<% for product in @products %>
<div class="product">
<h3>
<%= link_to h(product.name), product %>
<%= number_to_currency(product.price) %>
</h3>
</div>
<% end %>
上面?$(".apple_pagination a") x will_paginate ?:class Q:renderer 使用的是will_paginate 的default 的,如果 enviroment.rb 中配|了will_paginate的样式,q里不写 :renderer 会出错!Q具体默认的参数 可以查看 will_paginate 下的 view_helpers.rb
全部 源码 下蝲Q?br />
http://www.uushare.com/user/fl1429/file/1941241
配置ҎQ?br />
1Q进入工E, rake setup
2,ruby script/server
3,okay 成功 了。。。?br />
补充 Q?如果 一?面 有两处需?分页Q那?will_paginate 默认 情况?是同时翻늚。。那?如何 避免呢。。只需?l各自的 will_paginate 指定 不同?class 卛_ 例如
will_paginate :
<%= will_paginate collection ,
:class => "apple_paginate my_paginate",
:previous_label => '<<上一?,
:next_label => '下一?gt;>' ,
:renderer => 'WillPaginate::LinkRenderer' %>
apple_paginate ?分页的真正的 cssQmy_paginate 是ؓ?区别 不同区的 分页 而加?br />
jquery script :
jQuery(function() {
jQuery(".my_paginate a").live("click", function() {
jQuery(".my_paginate").html("正在加蝲...");
jQuery.get(this.href, {flag : "my" }, null, 'script');
return false;
});
});
注意 jquery get Ҏ?四个参数 ?意义
ref:
http://railscasts.com/episodes/174-pagination-with-ajax
http://soylentfoo.jnewland.com/articles/2007/09/17/resource_this-dry-rails-resource-controllers
http://book.csdn.net/bookfiles/375/10037514155.shtml
http://stackoverflow.com/questions/1268383/format-js-with-rails
]]>
查了下, ?p 是经q?inspect 的,inspect的字面意思是 ?Q貌?是检?占位W?Q但是还是云里雾?br />
看两个demo
oneQ?br />
p "a", "\nb"
l果Q?br />"a"
"\nb"
two:
class SomeClass
def initialize (arg_1, arg_2) # called with SomeClass.new
@member_1 = arg_1
@member_2 = arg_2
end
def print
puts "member_1: " + @member_1
puts "member_2: " + @member_2
end
end
sc1 = SomeClass.new('foo', 'bar')
puts sc1.inspect
p sc1
puts sc1
l果Q?br />#<SomeClass:0xb7c091b4 @member_1="foo", @member_2="bar">
#<SomeClass:0xb7c091b4 @member_1="foo", @member_2="bar">
#<SomeClass:0xb7c091b4>
q有是我们 最常用到的。。。查询数据库中一条数据记录集
@post = BlogPost.find(params[:id])
p @post
puts @post
l果Q?br />#<BlogPost id: 18, blog_id: 30, topic_id: nil, client_info_id: nil, title: "试", body: "试试试试试试试试?..", blog_post_comments_count: 0, type: "BlogPost", created_at: "2009-08-24 03:56:27", updated_at: "2009-08-24 03:56:27">
#<BlogPost:0xb595b8b0>
q样 看v?更一目了然。。?p 把数据库中的 字段 和?都输?了, puts 只输?一?对象的标识。。?br />
refQ?br />http://www.adp-gmbh.ch/ruby/language/inspect.html
http://stackoverflow.com/questions/1255324/p-vs-puts-in-ruby
http://blog.chinaunix.net/u1/37038/showart_489434.html
]]>
a = "a?中文aaa"
b = 'test'
p a.size # 17 Q可以看Z个中文字W在ruby中是3个英文字W)
p b.length # 4
puts a.slice(0,13) # a?中� slice method Q?是start下标处,13是lengthQ?/font>
最后一个输出最?是ؕ码,在java中是unicode~码没有这个问题,所以我们需要{换下~码来解冟뀂?br />
例如在rails?application_helper.rb 定义一个{换的Ҏ
def cut_string(charset,src,start,length)
require "iconv"
@conv=Iconv.new("UTF-16",charset)
@reverse_conv=Iconv.new(charset,"UTF-16")
p_start=start.class==Fixnum&&start>=0
p_length=length.class==Fixnum&&length>=0
return "" unless src&&p_start&&p_length
src_utf16=@conv.iconv(src)
cutted_src_utf_16=src_utf16[2*start+2,2*length]
@reverse_conv.iconv(cutted_src_utf_16)
end
view中用:
<%
a = 'a 试中?
puts cut_string('UTF-8',a,0,4) # a ?br />
%>
ref:
http://my.opera.com/sawpad/blog/show.dml/235183
http://www.javaeye.com/topic/201531
补充Q?br />
真伤心,之前截取字符Ԍ用上面的ҎQ还需要自己封装,自己转码解决Q没惛_rails已经把我们封装好了。。就?truncate Ҏ。。看了下源码真简单,只需要输出对应字W串的chars p决了Q源码:
def truncate(text, length = 30, truncate_string = "...")
if text
l = length - truncate_string.chars.length
chars = text.chars
(chars.length > length ? chars[0...l] + truncate_string : text).to_s
end
end
使用demoQ?br />
<%
a = 'test'
b = '试中文'
p truncate(a,2,'...') # "tes..."
p truncate(b,2,'...') # "试?.."
%>
如果需要得到汉字的长度 可以使用 jcode ?里的 jlength
demo:
s = "试140字测?40字测?40字测?40字测?40字测?40字测?40字测?40字测?40字测?40字测?40字测?40字测?40字测?br />
140字测?40字测?40字测?40字测?40字测?40字测?40字测?40字测?40字测?"
$KCODE='utf8'
require 'jcode'
p s.jsize
p s.jlength
ref:
http://blog.guoshuang.com/?p=4769
http://lifegoo.pluskid.org/?p=257
]]>
在用到rails <%= time_ago_in_words(activity.created_at).capitalize %> 之前 Ҏ?Q?输出的结果默认是英文的。。如?br />
需要重写原来的ҎQ用的是rails2.1.0 如果是rails 2.2.2之后的,貌似可以使用I18N的。。所以只好重写method?br />
刚开始是攑֜lib下, 然后在enviroment.rb中require的,但是后来没有成功Q只好放在initializers中了
新徏 date_helper.rb:(可以随便命名)
module ActionView
module Helpers
module DateHelper
def distance_of_time_in_words(from_time, to_time = 0, include_seconds = false)
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
distance_in_minutes = (((to_time - from_time).abs)/60).round
distance_in_seconds = ((to_time - from_time).abs).round
case distance_in_minutes
when 0..1
return (distance_in_minutes == 0) ? '于1分钟' : '1 分钟' unless include_seconds
case distance_in_seconds
when 0..4 then '于 5 U?
when 5..9 then '于 10 U?
when 10..19 then '于 20 U?
when 20..39 then '半分?
when 40..59 then '于 1 分钟'
else '1 分钟'
end
when 2..44 then "#{distance_in_minutes} 分钟"
when 45..89 then '大概 1 时'
when 90..1439 then "大概 #{(distance_in_minutes.to_f / 60.0).round} 时"
when 1440..2879 then '1 ?
when 2880..43199 then "#{(distance_in_minutes / 1440).round} ?
when 43200..86399 then '大概 1 个月'
when 86400..525599 then "#{(distance_in_minutes / 43200).round} 个月"
when 525600..1051199 then '大概 1 q?
else "过 #{(distance_in_minutes / 525600).round} q?
end
end
end
end
end
原来的方法,可以?br />
/usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_view/helpers/date_helper.rb 中找?br />
之后重启服务Qokay了。。。。。?br />
refQ?br />
http://www.nabble.com/Rails-2.1-and-ddatetime_select-td17726324.html
http://hervalicio.us/blog/2007/05/10/translating-time_ago_in_words/#comment-16360
http://fsjoy.blog.51cto.com/318484/119541
]]>
打开 http://www.google.cn/finance?q=600001 q个|址 可以看到 h财经?右侧 有个新闻区。。。这个新d是从别的地Ҏ取来?br />
截图Q?br />
现在我们也来仿照它来实现一个,首先rails解析rss有两U方式,一U是用封装好的类库,一U是用原始的解析xml的方?或者利用别人封装好的库 例如feedtools, rubyrss {?br />
用类库的ҎQ?br />
require 'rss/2.0'
require 'open-uri'
url = "http://news.google.cn/news?pz=1&ned=ccn&hl=zh-CN&topic=b&output=rss"
@feed = RSS::Parser.parse(open(url).read, false)
@feed.items.each do |item|
puts item.title
puts item.link
puts item.description
end
解析xml的方法:
在lib下徏立一个RssParser的类Q这样在M地方都可以调?br />
class RssParser
require 'rexml/document'
def self.run(url)
xml = REXML::Document.new Net::HTTP.get(URI.parse(url))
data = {
:title => xml.root.elements['channel/title'].text,
:home_url => xml.root.elements['channel/link'].text,
:rss_url => url,
:items => []
}
xml.elements.each '//item' do |item|
new_items = {} and item.elements.each do |e|
new_items[e.name.gsub(/^dc:(\w)/,"\1").to_sym] = e.text
end
data[:items] << new_items
end
data
end
end
action中用:
def test
feed = RssParser.run("http://news.google.cn/news?pz=1&ned=ccn&hl=zh-CN&topic=b&output=rss")
feed1 = feed[:items][0]
feed2 = feed[:items][0]
feed3 = feed[:items][0]
# combine the feeds into an array
@feeds = [feed1, feed2, feed3]
# parse the pubDate strings into a DateTime object
@feeds.each {|x| x[:pubDate] = DateTime.parse(x[:pubDate].to_s)}
# iterate through each feed, sorting by pubDate
@feeds.sort! {|a,b| a[:pubDate] <=> b[:pubDate]}
# reverse the array to sort by descending pubDate
@feeds.reverse!
@feeds.each do |feed|
puts feed[:title]
puts feed[:link]
puts feed[:pubDate]
end
end
那么上面的title link description 是从哪里来的呢。。。这个是rss2.0的xmll构Q一般情况下是这LQ?br />
<?xml version="1.0" encoding="utf-8"?>
okay....已经成功了,我实现的截图Q?br />
<rss version="2.0">
<channel>
<title>Example Feed</title>
<description>Insert witty or insightful remark here</description>
<link>http://example.org/</link>
<lastBuildDate>Sat, 13 Dec 2003 18:30:02 GMT</lastBuildDate>
<managingEditor>johndoe@example.com (John Doe)</managingEditor>
<item>
<title>Atom-Powered Robots Run Amok</title>
<link>http://example.org/2003/12/13/atom03</link>
<guid isPermaLink="false">urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</guid>
<pubDate>Sat, 13 Dec 2003 18:30:02 GMT</pubDate>
<description>Some text.</description>
</item>
</channel>
</rss>
或者你可以查看rss的页面源代码Q或者puts?nbsp; @feed = RSS::Parser.parse(open(url).read, false)的结果都可以看到上面的这中xml文l构
好,下面我们开始实C面图的新闻:
我们可以把这个部分放在partial里,所以只需要helper和partial文g
helperQ?br />
def feed_collection(param)
require 'rss/2.0'
require 'open-uri'
# from news.google.cn
urlhot = "http://news.google.cn/news?pz=1&ned=ccn&hl=zh-CN&topic=b&output=rss"
urlfinance = "http://news.google.cn/news?pz=1&ned=ccn&hl=zh-CN&topic=ecn&output=rss"
urlfund = "http://news.google.cn/news?pz=1&ned=ccn&hl=zh-CN&topic=stc&output=rss"
urlfinancing = "http://news.google.cn/news?pz=1&ned=ccn&hl=zh-CN&topic=pf&output=rss"
case param
when 'hot'
RSS::Parser.parse(open(urlhot).read, false)
when 'finance'
RSS::Parser.parse(open(urlfinance).read, false)
when 'fund'
RSS::Parser.parse(open(urlfund).read, false)
when 'financing'
RSS::Parser.parse(open(urlfinancing).read, false)
end
end
def feed_link(param)
require 'cgi'
CGI.unescape(param.slice(/(http%).*(&)/)).gsub(/&/,'') if param # 把十六进制\?例如http%3A2F之类的{化ؓ 字符
end
def feed_title(param)
param.slice(/.*(-)/).gsub(/-/,"") if param #截取需要的title
end
def feed_from(param)
param.slice(/( - ).*/).from(2) if param # 截取需要的部分
end
partial: _feednews.erb.html
<div class="slides">
<div><%= render :partial => 'shared/feednews_item',:collection => feed_collection("hot").items %></div>
<div><%= render :partial => 'shared/feednews_item',:collection => feed_collection('finance').items %></div>
<div><%= render :partial => 'shared/feednews_item',:collection => feed_collection('fund').items %></div>
<div><%= render :partial => 'shared/feednews_item',:collection => feed_collection('financing').items %></div>
</div>
Mq里参考了 jquery的loopslider 插gQ灯片Q?加蝲昄的只是第一个div部分Q可以参考:
http://github.com/nathansearles/loopedSlider/tree/master
partial: _feednews_item.html.erb
<ul>
<% unless feednews_item.nil? %>
<li class="news"><a href="<%= feed_link(feednews_item.link) %>" target="_blank"><%= feed_title(feednews_item.title) %></a>
<span class="grey small"><span> <%= feed_from(feednews_item.title) %></span> — <span><%= feednews_item.pubDate.to_date %></span></span></li>
<% end %>
</ul>
ref:
http://www.rubycentral.com/book/ref_c_string.html
http://www.javaeye.com/topic/60620
http://www.troubleshooters.com/codecorn/ruby/basictutorial.htm#_Regular_Expressions
http://paranimage.com/15-jquery-slideshow-plugins/#respond
http://hi.baidu.com/todayz/blog/item/83c1b219d966fd4142a9ad5f.html
http://dennis-zane.javaeye.com/blog/57538
http://sporkmonger.com/projects/feedtools/
http://rubyrss.com/
http://rubyrss.com/
http://www.superwick.com/archives/2007/06/09/rss-feed-parsing-in-ruby-on-rails/
http://www.ruby-forum.com/topic/144447
]]>
Rails ?partial ?传?collectionQ默认的循环变量 ?partial的名字(U定Q。或者你x变变量名的话Q可以?:as 参数声明一个变量。。。不能用惯性思想 for ...........in........{?br />
例如Q?br />
之前错误的写法:
partial : _feednews.html.erb
<%= render :partial => 'shared/feednews_item',:collection => @feeds = feed_collection("hot").items %>
partial : _feednews_item.html.erb
<ul>
<% for feed in @feeds.items %>
<li class="news"><a href="<%= feed_link(feed.link) %>" target="_blank"><%= feed_title(feed.title) %></a><br />
<span class="grey small"><span> <%= feed_from(feed.title) %></span> — <span><%= feed.pubDate.to_date %></span></span></li>
<% end %>
</ul>
上面W二?partial 昄的结?for 循环 输出 后的 加上 rails U定的partial collection 循环输出了。。结果重复。。做的过E中q遇?partial collection empty q个异常
原因? feed_collection("hot").items q回的结果不是一?collection..
正确的写法:
partial : _feednews.html.erb
<div><%= render :partial => 'shared/feednews_item',:collection => feed_collection("hot").items %></div>
partial : _feednews_item.html.erb
<ul>
<% unless feednews_item.nil? %>
<li class="news"><a href="<%= feed_link(feednews_item.link) %>" target="_blank"><%= feed_title(feednews_item.title) %></a><br />
<span class="grey small"><span> <%= feed_from(feednews_item.title) %></span> — <span><%= feednews_item.pubDate.to_date %></span></span></li>
<% end %>
</ul>
从上面的prtial中可以看?变量 是feednews_item 也就是partial的名?br />
ȝQ一句话Q如?你在 partial ?传了 collection ,那么 q partial的名?作变量输出, 不需?q代Q?如果 没有 传collection Q?那么 需?q代输出Q?br />
]]>
有这样一个需求,需要用?虚拟兌
在SNS中,例如xiaoneiQdouban{等都有 最q好友更新的内容昄Q那么这?一般是在一?表中Q例?叫activities 表,更新有很多种 Q例?修改头像Q发表日志,建立了好友关p,发表评论{等Q。。说白了是 一个表 兌?多个表,那就得用?虚拟 兌了。?br />
表结构:
原理Q?br />
上面有三个表Qactivities表(记录更新了那些操作,最重要的两个字D|item_id,和item_type,item_id是对应到兌表的主键idQitem_type是对应到兌表的表对象名例如comments表就是CommentQ?Posts?Q用户发表文字的表,例如有发表blog的blog_id,发表论坛 topic?topic_id,l用La的client_info_id,body是发表的内容Q,
comments表(评论表,body是评论内容,当然评论也好好多U评论,q个表里也需要关联许多表Q从comments表的字段中也可以看到用了虚拟兌Q?br />
用法Q?br />
model:
activity
class Activity < ActiveRecord::Base
................
belongs_to :item, :polymorphic => true
..........................
end
Comment
..................
has_many :activities, :foreign_key => "item_id" , :dependent => :destroy
..................
加上 :dependent => :destroy 是当q条评论删除Ӟactivities 表里的记录同时被删除
或者:
has_many :activities, :as => :item , :dependent => :destroy
那么 Post 模型 同理可得。。。?
因ؓ上面?:item Q?所?activities 表里?item_id Q?nbsp; item_type 是约定俗成的。。。。。。。。?br />
取数?br />
activity.item.body
activity 是activities表中的记录对?br />
refQ?br />
http://guides.rails.info/association_basics.html
http://hideto.javaeye.com/blog/76709
http://hi.baidu.com/rainchen/blog/item/fc3a94eeb31ad62b2df53412.html
http://iceskysl.1sters.com/?action=show&id=25
http://rubycnrails.cn/articles/23 Q了?dependent=>:destroyQ?br />
]]>
view:
<div id="activity_<%=activity.id%>" class="blog_item clearfix">
..........
<%= link_to_remote image_tag("/images/icons/network/close.gif"),
:url => {:controller=>'activities', :action =>'destroy',:id=>activity.id },
:method => :delete,
:confirm => %(认删除更新?)
%>
</div>
controller:
def destroy
@activity.destroy
# flash[:notice] = "状态已删除"
respond_to do |format|
format.html { redirect_to :back }
format.xml { head :ok }
format.js do
render :update do |page|
page.remove "activity_#{@activity.id}"
end
end
end
end
refQ?br />http://scottmotte.com/archives/62.html
]]>
我们知道rails中分一般是will_paginate插g Q?如果惛_现twitter那样的more的方式,那就得用到will_paginate插g ?ajax的操作了Q核心思想是在div id 的bottom?insert_html , 比原来的直接 will_paginate E微复杂一点,|上有很多是像greader那样的滚屏自动加载的Ҏ google一?endless pagination 有很多
效果Q?br />
源码下蝲Q?br />
http://www.uushare.com/user/fl1429/file/1882575
下蝲后用方法:
1Q配|连接mysql数据库的ymlQƈ在数据库中徏立相信的db
2Q进入工E?rake db:migrate
3,在数据库中添加一些数?br />
4Qokay 启动试
另附滚屏加蝲的代码下载,配置使用Ҏ ?上面cM
http://www.uushare.com/user/fl1429/file/1882506
ref:
http://net.tutsplus.com/tutorials/javascript-ajax/create-a-twitter-like-load-more-widget/
http://d.hatena.ne.jp/hichiriki/20090415/1239751466
http://github.com/jney/jquery.pageless/blob/90213b1168ef23718e7dd8989e593f7e3a2d5c6d/README.textile
http://www.railsillustrated.com/screencast-endless-page.html
]]>
localhost:8808 览。。。?br />
唯一的好处是可以查看电脑里安装所有的gem rdoc
]]>
demo:
delaware = { 1 => "Two", 2 => "New Value", 3 => "New Three" , 8 => "Five" }
myhash = { 1 => "One", 2 => "Two", 3 => "Three", 4 => "Four", 5 => "Five" }
puts delaware
puts myhash
puts delaware.merge(myhash)
puts myhash.merge(delaware)
l果Q?br />1Two2New Value8Five3New Three
5Five1One2Two3Three4Four
5Five1One2Two8Five3Three4Four
5Five1Two2New Value8Five3New Three4Four
refQ?br />http://ruby-doc.org/core/classes/Hash.html#M002880
http://www.java2s.com/Code/Ruby/Hash/Mergetwohashes.htm
http://simohayha.javaeye.com/blog/151947
]]>
下蝲地址:
http://www.dbank.com/download.action?k=8004b8cb15a44b28ab630551eb7658df
or
http://www.uushare.com/filedownload?user=fl1429&id=2018924
下蝲?安装一个exe文g和一个gem文g
one : 点击exe安装
two:
gem install rmagick.gem
three:
不行的話重新起下電腦Q嘿嘿~
ref:
http://www.opensourceconnections.com/2007/10/06/installing-rmagick-on-windows-using-ruby-186/
从ruby-lang下蝲ruby1.8.6的installer,点击安装
two:
gem install rails -v=2.1.0
判断成功:
ruby –v
gem –v
rails -v
环境Q?/font>ubuntu 8.10 en version
安装ror版本 Q?ruby 1.8.7 + rails 2.1.0
1,安装ruby
sudo apt-get ruby
安装l束?可以?/font>ruby -v 查看安装l果
feng@feng:~$ ruby -v
ruby 1.8.7 (2008-08-11 patchlevel 72) [i486-linux]
2Q安?/font>rubygems
sudo apt-get rubygems
安装l束后可以用 gem -v 查看安装l果
feng@feng:~$ gem -v
1.3.4
3Q安装完rubygems后可能不是最新版Q需要更C下,更新的方?/font>
$ sudo gem install rubygems-update
4Q安?/font>rails
sudo gem install -v=2.1.0 rails
安装l束后,可以?rails -v 查看下安装结?/font>
feng@feng:~$ rails -v
Rails 2.1.0
刚开始我用的?/font>sudo gem install rails,安装的是最新版Q但是和ruby1.8.7不协调,最后又怺railsQ重新装?/font>rails 2.1.0Q卸载方式如下:
gem list 列出所?/font>gem包,
feng@feng:~$ gem list
*** LOCAL GEMS ***
actionmailer (2.1.0)
actionpack (2.1.0)
activerecord (2.1.0)
activeresource (2.1.0)
activesupport (2.1.0)
calendar_date_select (1.15)
rails (2.1.0)
rake (0.8.7)
rmagick (2.9.2)
然后逐一删除
sudo gem uninstall rails
sudo gem uninstall actionmailer
?/font>
?/font>
?/font>
refQ?/font>
http://hi.baidu.com/pepsichan/blog/item/dc1e030a58c9021795ca6bde.html
http://hi.baidu.com/pepsichan/blog/item/8cf53dec6957432f62d09f1c.html
Magick::AspectGeometry
ok?br />
我的demoQ?br />
apiQ?br /> http://www.simplesystems.org/RMagick/doc/struct.html#Geometry