forked from notahat/machinist
/
sequel.rb
69 lines (60 loc) · 1.89 KB
/
sequel.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
require 'machinist'
require 'machinist/blueprints'
require 'sequel'
module Machinist
class SequelAdapter
def self.has_association?(object, attribute)
object.class.associations.include?(attribute)
end
def self.class_for_association(object, attribute)
object.class.association_reflection(attribute).associated_class
end
def self.assign_attribute(object, attribute, value)
if Machinist.nerfed? && has_association?(object, attribute)
object.associations[attribute] = value
else
object.send("#{attribute}=", value)
end
end
def self.assigned_attributes_without_associations(lathe)
attributes = {}
lathe.assigned_attributes.each_pair do |attribute, value|
association = lathe.object.class.association_reflection(attribute)
if association && association[:type] == :many_to_one
key = association[:key] || association.default_key
attributes[key] = value.send(association.primary_key)
else
attributes[attribute] = value
end
end
attributes
end
end
module SequelExtensions
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def make(*args, &block)
lathe = Lathe.run(Machinist::SequelAdapter, self.new, *args)
unless Machinist.nerfed?
lathe.object.save(:raise_on_failure => true)
end
lathe.object(&block)
end
def make_unsaved(*args)
returning(Machinist.with_save_nerfed { make(*args) }) do |object|
yield object if block_given?
end
end
def plan(*args)
lathe = Lathe.run(Machinist::SequelAdapter, self.new, *args)
Machinist::SequelAdapter.assigned_attributes_without_associations(lathe)
end
end
end
end
class Sequel::Model
include Machinist::Blueprints
include Machinist::SequelExtensions
end