Last active
August 16, 2016 07:08
-
-
Save Shinpeim/1b54be49baa55ce615f8c7f2417203aa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "active_record" | |
# DB接続設定 | |
ActiveRecord::Base.establish_connection( | |
adapter: "sqlite3", | |
database: ':memory:' | |
) | |
# スキーマの設定 | |
class InitialSchema < ActiveRecord::Migration | |
def self.up | |
create_table :users do |t| | |
t.string :first_name | |
t.string :last_name | |
end | |
end | |
def self.down | |
drop_table :users | |
end | |
end | |
InitialSchema.migrate(:up) | |
module FirstNameValidtionContext | |
def self.included(klass) | |
klass.instance_eval do |i| | |
validates :first_name, presence: true | |
end | |
end | |
end | |
module LastNameValidtionContext | |
def self.included(klass) | |
klass.instance_eval do |i| | |
validates :last_name, presence: true | |
end | |
end | |
end | |
class User < ActiveRecord::Base | |
end | |
class UserWithFirstNameValidationContext < User | |
include FirstNameValidtionContext | |
end | |
class UserWithLastNameValidationContext < User | |
include LastNameValidtionContext | |
end | |
u = UserWithFirstNameValidationContext.new | |
u.first_name = ""; | |
u.last_name = "akasaki"; | |
p u.validate # => false | |
u.first_name = "tsukika"; | |
p u.validate # => true | |
u = UserWithLastNameValidationContext.new | |
u.first_name = "tsukika"; | |
u.last_name = ""; | |
p u.validate # => false | |
u.last_name = "akasaki"; | |
p u.validate # => true | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment