推荐的方式或插件为rails应用程序上的ruby创建谷歌站点地图?
我做了一个快速的谷歌搜索,并没有看到任何超级伟大的自动创建和更新我的谷歌站点地图为ruby on rails应用程序。 有什么建议?
我刚刚在博客应用程序中添加了动态站点地图。 这些步骤可以帮助您入门。
将此路由添加到config/routes.rb
文件的底部(应在其上方列出更具体的路由):
map.sitemap '/sitemap.xml', :controller => 'sitemap'
创建SitemapController
(app / controllers / sitemap_controller):
class SitemapController < ApplicationController layout nil def index headers['Content-Type'] = 'application/xml' last_post = Post.last if stale?(:etag => last_post, :last_modified => last_post.updated_at.utc) respond_to do |format| format.xml { @posts = Post.sitemap } # sitemap is a named scope end end end end
– 正如您所看到的,这适用于博客,因此使用Post
模型。
这是视图模板(app / views / sitemap / index.xml.builder):
base_url = "http://#{request.host_with_port}" xml.instruct! :xml, :version=>'1.0' xml.tag! 'urlset', 'xmlns' => 'http://www.sitemaps.org/schemas/sitemap/0.9' do for post in @posts do xml.tag! 'url' do xml.tag! 'loc', "#{base_url}#{post.permalink}" xml.tag! 'lastmod', post.last_modified xml.tag! 'changefreq', 'monthly' xml.tag! 'priority', '0.5' end end end
而已! 您可以通过在浏览器中显示http:// localhost:3000 / sitemap.xml (如果使用Mongrel)或者使用cURL来测试它。
请注意,控制器使用stale?
如果自上次请求站点地图以来没有新post,则发出HTTP 304未修改响应的方法。
我真的不建议使用控制器,只需像’/sitemap.xml’那样路由它,因为如果你的站点地图会增长,它将浪费资源。 最好每晚做一次rake任务并重新生成站点地图,具体取决于内容更改的频率。
如果您的网站没有接近50000页的任何地方并且您没有计划拥有更多,那么您可以放入一个站点地图文件,那么我建议您使用“ 使用Ruby on Rails,Capistrano和Cron的Google Sitemaps ”我知道它可以正常工作因为我成功地使用了它。
注意:我不建议每次运行部署任务时都使用作者复制站点地图的方式,在我看来它并不干净。 最好在部署时使用共享目录和符号链接,然后你肯定只有一个版本的文件,如果留下额外的副本,现在浪费空间。 我在deploy.rb中有这个:
desc "Symlink the upload directories" task :before_symlink do run "rm -drf #{release_path}/public/sitemaps" run "ln -s #{shared_path}/sitemaps #{release_path}/public/sitemaps" end
你也可以使用“ 大站点地图 ”gem,但我刚才发现它并不能告诉你它有多好。 看起来设置这个gem真的很容易,它也使用你的rails路由来生成链接,所以你要解决的问题比第一个解决方案少。
Google Sitemap生成器是Google的官方发布。 它易于设置和配置。
我建议您查看sitemap_generator gem 。 它为你处理所有这些问题…而且,真的,谁想要搞乱创作XML?
下面是一个示例站点地图,显示您如何使用Rails模型和路径助手生成站点地图URL:
# config/sitemap.rb SitemapGenerator::Sitemap.default_host = "http://www.example.com" SitemapGenerator::Sitemap.create do add '/contact_us' Content.find_each do |content| add content_path(content), :lastmod => content.updated_at end end
然后,您可以根据需要使用Rake任务进行刷新。 真的很简单:)
- javascript函数可通过javascript_include_tag获得,但不是资产管道和application.js
- RMagick面具Paperclip图像附件
- 黄瓜矛盾的错误信息
- Mailchimp gem double_optin false不能正常工作
- Rails db:seed error“undefined method`finder_needs_type_condition?’ 为零:NilClass“
- 保存到PostgreSQL时,二进制数据变得笨拙
- Rails:切换用户Gem以及切换回原始用户的问题
- 如何在js.html.erb文件中返回index.html.erb
- 将标头附加到Rspec控制器测试