Use a Railtie to extend Rails
This commit is contained in:
parent
4a333d7276
commit
2b01d8ce70
@ -1,20 +1,18 @@
|
|||||||
# frozen_string_literal: true
|
# frozen_string_literal: true
|
||||||
|
|
||||||
if defined?(::ActiveRecord)
|
::ActiveRecord::Associations::Builder::HasOne.class_eval do
|
||||||
::ActiveRecord::Associations::Builder::HasOne.class_eval do
|
# Based on
|
||||||
# Based on
|
# https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/builder/collection_association.rb#L50
|
||||||
# https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/builder/collection_association.rb#L50
|
# https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/builder/singular_association.rb#L11
|
||||||
# https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/builder/singular_association.rb#L11
|
def self.define_accessors(mixin, reflection)
|
||||||
def self.define_accessors(mixin, reflection)
|
super
|
||||||
super
|
name = reflection.name
|
||||||
name = reflection.name
|
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
|
||||||
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
|
def #{name}_id
|
||||||
def #{name}_id
|
# if an attribute is already defined with this methods name we should just use it
|
||||||
# if an attribute is already defined with this methods name we should just use it
|
return read_attribute(__method__) if has_attribute?(__method__)
|
||||||
return read_attribute(__method__) if has_attribute?(__method__)
|
association(:#{name}).reader.try(:id)
|
||||||
association(:#{name}).reader.try(:id)
|
end
|
||||||
end
|
CODE
|
||||||
CODE
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
@ -2,5 +2,9 @@
|
|||||||
|
|
||||||
module FastJsonapi
|
module FastJsonapi
|
||||||
require 'fast_jsonapi/object_serializer'
|
require 'fast_jsonapi/object_serializer'
|
||||||
require 'extensions/has_one'
|
if defined?(::Rails)
|
||||||
|
require 'fast_jsonapi/railtie'
|
||||||
|
elsif defined?(::ActiveRecord)
|
||||||
|
require 'extensions/has_one'
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
11
lib/fast_jsonapi/railtie.rb
Normal file
11
lib/fast_jsonapi/railtie.rb
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
# frozen_string_literal: true
|
||||||
|
|
||||||
|
require 'rails/railtie'
|
||||||
|
|
||||||
|
class Railtie < Rails::Railtie
|
||||||
|
initializer 'fast_jsonapi.active_record' do
|
||||||
|
ActiveSupport.on_load :active_record do
|
||||||
|
require 'extensions/has_one'
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
Loading…
x
Reference in New Issue
Block a user