@@ -12,8 +12,8 @@ class Model
1212 validate :file_contents_present , if : proc { |me | me . file . present? }
1313
1414
15- before_validation :uncompress_file , if : proc { |me | me . archive? && me . allow_archive? }
16- before_validation :encode_file , if : proc { |me | me . force_encoding? && me . file . present? }
15+ before_validation :uncompress_file , if : proc { |me | me . archive? && me . allow_archive? }
16+ before_validation :encode_file , if : proc { |me | me . force_encoding? && me . file . present? }
1717
1818 attr_reader :attributes
1919
@@ -28,12 +28,7 @@ def assign_attributes(args = {}, new_record = false)
2828 @attributes . merge! ( args )
2929 @new_record = new_record
3030 args . keys . each do |key |
31- key = key . to_sym
32- #generate methods for instance object by attributes
33- singleton_class . class_eval do
34- define_method ( key ) { self . attributes [ key ] } unless method_defined? key
35- define_method ( "#{ key } =" ) { |new_value | @attributes [ key ] = new_value } unless method_defined? "#{ key } ="
36- end
31+ define_methods_for ( key . to_sym )
3732 end if args . is_a? ( Hash )
3833 end
3934
@@ -82,7 +77,7 @@ def file_path
8277 def encode_file
8378 data = File . read ( file_path ) . encode ( force_encoding , invalid : :replace , undef : :replace )
8479 File . open ( file_path , 'w' ) do |f |
85- f . write ( data )
80+ f . write ( data )
8681 end
8782 end
8883
@@ -126,6 +121,28 @@ def file_type
126121 ''
127122 end
128123 end
124+
125+ protected
126+
127+ def define_methods_for ( attr_name )
128+ #generate methods for instance object by attributes
129+ singleton_class . class_eval do
130+ define_set_method ( attr_name )
131+ define_get_method ( attr_name )
132+ end
133+ end
134+
135+
136+ class <<self
137+ def define_set_method ( attr_name )
138+ define_method ( attr_name ) { self . attributes [ attr_name ] } unless method_defined? attr_name
139+ end
140+
141+ def define_get_method ( attr_name )
142+ define_method ( "#{ attr_name } =" ) { |new_value | @attributes [ attr_name ] = new_value } unless method_defined? "#{ attr_name } ="
143+ end
144+ end
145+
129146 end
130147end
131148
0 commit comments