require 'cgi'CGI.escape(url)require 'cgi'CGI.escape(url)HAMLである条件がtrueの時だけあるclassをタグに追加したい場合
.post{:class => ("gray" unless post.published?)}
ActionView/Helpers/AssetTagHelper、asset(画像、CSSなど)ホストのチューニングについての勉強メモです。
Gistのmarkdownはembedする時にうまくスタイルをレンダリングしてくれないようです。。。
orz….https://gist.github.com/1350279で見たほうがいいかも知れません。
## asset hostを指定image_tag("rails.png")のhelper methodで生成するリンクはデフォルトでは同じホストのpublicフォルダを指しています。それを変更したい場合は`config/environments/production.rb`の`ActionController::Base.asset_host`をいじります。
```rubyActionController::Base.asset_host = "assets.example.com"```
```erbimage_tag("rails.png")# => <img alt="Rails" src="http://assets.example.com/images/rails.png?1230601161" />```
## asset hostを複数指定ブラウザが一度に同一サーバには2つのコネクションしかできないそう(これは初めて知りました)で、asset同士のダウンロード完了するのを待たなければなりません。もし複数台のassetサーバがある場合は`assets%d.example.com`を使ってそれをコネクション数を増やせることができます。`%d`が指定されればRailsは0~3の4つの番号を付けて、並行して8つのコネクションができます。
```rubyActionController::Base.asset_host = "assets%d.example.com"```
```erbimage_tag("rails.png")# => <img alt="Rails" src="http://assets.example.com/images/rails.png?1230601161" />stylesheet_link_tag("application")# => <link href="http://assets2.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" />```
### カスタマイズもっと自分でカスタマイズしたい場合は`source`のprocパラメータを使えます。
```rubyActionController::Base.asset_host = Proc.new { |source| "http://assets#{Digest::MD5.hexdigest(source).to_i(16) % 2 + 1}.example.com"}image_tag("rails.png")# => <img alt="Rails" src="http://assets1.example.com/images/rails.png?1230601161" />stylesheet_link_tag("application")# => <link href="http://assets2.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" />```
特定のパスで始まるassetを特定のホストに指定する例:```rubyActionController::Base.asset_host = Proc.new { |source| if source.starts_with?('/images') "http://images.example.com" else "http://assets.example.com" end }```
```erbimage_tag("rails.png")# => <img alt="Rails" src="http://images.example.com/images/rails.png?1230601161" />stylesheet_link_tag("application")# => <link href="http://assets.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" />```さらに`request`の第二パラメータもあります。これでHTTPSの動作も制御できます。
```rubyActionController::Base.asset_host = Proc.new { |source, request| if request.ssl? "#{request.protocol}#{request.host_with_port}" else "#{request.protocol}assets.example.com" end}```
## Resourceshttp://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html例えば省略可能なフラグみたいなローカル変数をpartial viewに渡した時、そのデフォルト動作をpartial viewでハンドリングしたいですね。
<%= render 'article', :show_author => false %><%= render 'article' %>
調べてみたらdefined?と local_assigns.has_key?が見つかりましたが、前者のほうはオススメできなさそうです。
Testing using defined? headline will not work. This is an implementation restriction.
# http://api.rubyonrails.org/classes/ActionView/Base.html
# If you need to find out whether a certain local variable# has been assigned a value in a particular render call, # you need to use the following pattern:
<% unless local_assigns.has_key? :show_author %> <% show_author = true %><% end %>
<% if show_author %> Author: <%= @article.author %><% end %>
# Testing using defined? headline will not work. This is an implementation restriction.
実際やってみて、defined?でも動けるパターンはありますが、if/unless文で一行にしたらバグりました。なのでやはり local_assigns.has_key?を使いましょう。
# this will work<% unless defined?(:show_author) %> <% show_author = true %><% end %>
# NOT work<% show_author = true unless defined?(:show_author) %>
# this will work<% show_author = true unless local_assigns.has_key? :show_author %>http://stackoverflow.com/questions/238615/defined-method-in-ruby-and-rails
OmniauthでTwitterに認証ログイン後、ログイン前と同じページにリダイレクトしたい
# config/application.rb
config.middleware.use 'StoreRedirectTo'
# and make sure you autoload the contents of /lib
# lib/store_redirect_to.rb
class StoreRedirectTo def initialize(app) @app = app end
def call(env) request = Rack::Request.new(env) path = request.path signin = path.match(%r(^/auth/[^/]+$)) && path != '/auth/failure' signout = path == '/users/signout' if signin || signout redirect = request.params['redirect_to'] || request.referer request.session['redirect_to'] = redirect if redirect end
@app.call(env) endend# after successful sign-in or sign-outredirect_to session[:redirect_to] || root_pathsession[:redirect_to] = nillibディレクトリのautoloadはRails libディレクトリのファイルをautoloadを参考してください。
redirect_toパラメータ或いはrefererをログイン直前のリクエストから取ってセッションに保存するRack middwareの手法です。そしてsessions_controllerではセッション内に保存されたurlにリダイレクトし、セッションクリアしています。
もちろんTwitter以外のproviderでの認証&ログイン処理にも対応できます。
# application.rb
# Custom directories with classes and modules you want to be autoloadable.# config.autoload_paths += %W(#{config.root}/extras)config.autoload_paths += %W(#{config.root}/lib)config.autoload_paths += Dir["#{config.root}/lib/**/"]サブディスプレイのautoloadが必要ない場合は一行目だけでOK.
rvm get headrvm reloadrvm install 1.9.3-p0rvm use 1.9.3http://www.ruby-lang.org/ja/news/2011/10/31/ruby-1-9-3-p0-is-released/
結構速くなったらしいです。
この記事を参考:http://stjhimy.com/posts/24-ruby-1-9-3-freaking-fast-bro
Sinatraで静的なhtmlファイルをrenderする方法です。
Sinatraでは色々なビューテンプレートをレンダリングできます。Haml、Erb、Sass、Markdown、CoffeeScript…が対応されていますが、HTMLは対応してないようです。html :indexで書いてもダメですね。
require 'sinatra'
get '/' do File.read(File.join('public', 'index.html')) # or # send_file File.join(settings.public, 'index.html')endFile.readでファイルとして読み込むことですね。Sinatraはデフォルトの設定だとpublicフォルダ内のものをassetsとするそうです。
でちょっとリファクタリングしてhtml :indexのシンタックスでいけるようにしました。
require "sinatra"
get '/' do # File.read(File.join('public', 'index.html')) html :indexend
def html(view) File.read(File.join('public', "#{view.to_s}.html"))endhttp://stackoverflow.com/questions/2437390/serving-static-files-with-sinatra
よくつかうメソッドの nil? empty? blank? のまとめ。
nil? すべてのオブジェクトにある。nilのときにTrueを返す。
empty? 文字の長さが0のとき、配列が空のときにTrueを返す。
blank? railsの拡張。nil, “”, ” “, [], {} のいずれかでTrueを返す。
素晴らしいまとめですね!ootokageさんに感謝。
PHP使うときはempty(0)でtrueになりますが、上記のメソッドどれも0をチェックしないですね。。.zero?というのメソッドは一応あるようですが。
迷ったらここにいっぱいサンプルがあります。
0.nil? #=> false
0.zero? #= true
0.empty? #=> NoMethodError
0.blank? #=> false
0 == false #=> false
“”.nil? #=> false
“”.zero? #=> NoMethodError
“”.empty? #=> true
“”.blank? #=> true
“” == false #=> false
{}.nil? #=> false
{}.zero? #=> NoMethodError
{}.empty? #=> true
{}.blank? #=> true
{} == false #=> false
[].nil? #=> false
[].zero? #=> NoMethodError
[].empty? #=> true
[].blank? #=> true
[] == false #=> false
nil.nil? #=> true
nil.zero? #=> NoMethodError
nil.empty? #=> NoMethodError
nil.blank? #=> true
nil == false #=> false
false.nil? #=> false
false.zero? #=> NoMethodError
false.empty? #=> NoMethodError
false.blank? #=> true
false == false #=> true