Skip to content

Instantly share code, notes, and snippets.

@pinzolo
pinzolo / 00_tables.rb
Created December 10, 2015 06:02
Arel を使って複数テーブルから or 検索
# こんなテーブルがあるとします
create_table :users do |t|
t.string :name
t.string :email
end
create_table :belongings do |t|
t.integer :user_id
t.string :company_name
# Rails3
class Course < ActiveRecord::Base
has_many :students, order: :name, include: [:parents, :brothers], dependent: :destroy
end
# Rails4
class Course < ActiveRecord::Base
has_many :students, ->{ order(:name).includes(:parents, :brothers) }, dependent: :destroy
end
@pinzolo
pinzolo / assoc_opts.rb
Last active November 7, 2015 03:51
Patch class for has_many options style in Rails3 and Rails4
module AssocOpts
extend ActiveSupport::Concern
module ClassMethods
def assoc_opts(options)
return [options] if Gem::Version.new(Rails.version) < Gem::Version.new('4.0.0')
order_option = options.delete(:order)
include_option = options.delete(:include)
if order_option && include_option
@pinzolo
pinzolo / Rakefile
Last active October 30, 2015 10:36
Test my original gem by test-unit
require 'bundler/gem_tasks'
require 'rake/testtask'
Rake::TestTask.new do |t|
t.libs << 'test'
t.test_files = FileList['test/my_gem/*_test.rb']
t.verbose = true
end
task default: :test
class Point
attr_reader :x, :y
def initialize(x, y)
@x = x
@y = y
end
def ==(other)
@x == other.x && @y == other.y
@pinzolo
pinzolo / get_associated_attribute_names.rb
Last active August 29, 2015 14:05
アソシエーションで定義された属性の名前を取得する
user = User.first
# association で定義された属性の名前を取得
user.reflections.keys
# belongs_to で定義された属性の名前を取得
user.reflections.select { |_, ref| ref.macro == :belongs_to }.keys
# through 経由で定義された属性の名前を取得
user.reflections.select { |_, ref| ref.is_a?(ActiveRecord::Reflection::ThroughReflection) }.keys
require 'zip'
class ZipForWin
def zip_files(directory)
Zip::File.open("#{directory}.zip", Zip::File::CREATE) do |zipfile|
# 再帰的にサブディレクトリも格納する
Dir[File.join(directory, '**', '**')].each do |entry|
# 相対パスで格納
entry_path = entry.sub(directory, '')
# windows で解凍できるように Shift_JIS へ変換
module MyPlugin::Model
extend ActiveSupport::Concern
included do
__send__(:include, ActiveModel::Conversion)
__send__(:include, ActiveModel::Validations)
extend ActiveModel::Naming
extend ActiveModel::Translation
class << self
alias_method_chain :i18n_scope, :my_plugin_model
ja:
my_plugin_model:
errors:
messages:
inclusion: "は一覧にありません。"
exclusion: "は予約されています。"
invalid: "は不正な値です。"
confirmation: "が一致しません。"
accepted: "を受諾してください。"
empty: "を入力してください。"
ja:
activemodel:
errors:
messages:
inclusion: "は一覧にありません。"
exclusion: "は予約されています。"
invalid: "は不正な値です。"
confirmation: "が一致しません。"
accepted: "を受諾してください。"
empty: "を入力してください。"