Skip to content

Instantly share code, notes, and snippets.

@tigawa
tigawa / gist:4653270
Last active December 11, 2015 20:09
ruby rails 入力チェック
#app/models/product.rb
#必須入力チェック
validates :description, :image_url, :price, :title , presence: true
#数値属性チェック
validates :price , numericality: {greater_than_of_equal_to: 0.01}
#重複チェック
validates :title, uniqueness: true
@tigawa
tigawa / gist:4653784
Last active December 11, 2015 20:09
ruby マルチバイト文字
# encoding: utf-8
# ファイルの先頭に上記のコメントを追加する。
@tigawa
tigawa / gist:4664729
Created January 29, 2013 14:42
ruby rails モデルテスト
require 'test_helper'
class ProductTest < ActiveSupport::TestCase
test "product attributes must not be empty" do
product = Product.new
assert product.invalid?
assert product.errors[:title].any?
assert product.errors[:description].any?
assert product.errors[:price].any?
assert product.errors[:image_url].any?
@tigawa
tigawa / gist:4689398
Last active December 12, 2015 01:09
apache queryStringの入力内容により、リダイレクト先を切替える。
RewriteEngine on
RewriteCond %{QUERY_STRING} PARAM=03
RewriteRule ^/abc/(.*)$ /xyz1/$1 [R=301,L]
RewriteCond %{QUERY_STRING} PARAM=02 [OR]
RewriteCond %{QUERY_STRING} PARAM=04
RewriteRule ^/abc/(.*)$ /xyz2/$1 [R=301,L]
@tigawa
tigawa / gist:4731195
Created February 7, 2013 14:20
rails sanitize()メソッド
#HTMLのスタイルを摘要する事ができる。
<%= sanitize(product.description) %>
@tigawa
tigawa / gist:4732055
Created February 7, 2013 16:20
rails ruby フォーマット
sprintf("$%0.02f",product.price)
@tigawa
tigawa / gist:4736360
Last active December 12, 2015 07:28
rails ruby ボタンを追加する。 該当のcontrollerのcreate()メソッドが実行される。
<%= button_to 'カートに入れる', line_items_path(product_id: product) %>
#HTML 展開イメージ
#<pre><code class="html">
#<form action="/line_items?product_id=1" class="button_to" method="post">
# <div><input type="submit" value="カートに入れる">
# <input name="authenticity_token" type="hidden" value="4yQOh3nVUm6w27g/Ej1DiyWNhtVcdcQOvjDuyZeztGk=">
# </div>
#</form>
#</code></pre>
@tigawa
tigawa / gist:4950475
Created February 14, 2013 03:44
rails カラムを後から追加する方法
migrationの後ろに、追加すれば項目の追加、削除ができる。
add_XXX_to_TABLE
remove_XXX_TO_TABE
※XXXXの部分は無視されるらしいよ
#実行例
#rails g migration add_quantiy_to_line_items quantity:integer
@tigawa
tigawa / gist:5043102
Created February 26, 2013 22:50
ruby 2.0 lazy
require 'date'
def each_fridays
friday = Date.new(2013,1,4)
loop do
yield friday
friday += 7
end
end
fridays = enum_for(:each_fridays)
@tigawa
tigawa / gist:5043111
Created February 26, 2013 22:51
ruby 2.0 keyword param
def count_word_from_file(path: "~/default.txt", word:"default")
file = File.read(path)
return file.split.select{|w| w==word}.size
end