idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
1,900
def set_attrs ( hash , clobber = true , target = nil ) target ||= @attrs if clobber target . merge! ( hash ) hash else hash . each do | k , v | if v . is_a? ( Hash ) set_attrs ( v , clobber , target [ k ] ) else target [ k ] = v end end end end
Set the current attributes from a hash . If clobber is true any existing hash values will be clobbered by the new hash otherwise the hash will be deeply merged into attrs . The target paramater is for internal use only and should not be used .
1,901
def _run ( args : nil , reraise_errors : false ) if args . nil? && que_target args = que_target . que_attrs . fetch ( :args ) end run ( * args ) default_resolve_action if que_target && ! que_target . que_resolved rescue => error raise error unless que_target que_target . que_error = error run_error_notifier = begin handle_error ( error ) rescue => error_2 Que . notify_error ( error_2 , que_target . que_attrs ) true end Que . notify_error ( error , que_target . que_attrs ) if run_error_notifier retry_in_default_interval unless que_target . que_resolved raise error if reraise_errors end
Note that we delegate almost all methods to the result of the que_target method which could be one of a few things depending on the circumstance . Run the job with error handling and cleanup logic . Optionally support overriding the args because it s necessary when jobs are invoked from ActiveJob .
1,902
def handle_error ( error ) return unless que_target max = resolve_que_setting ( :maximum_retry_count ) if max && error_count > max expire else retry_in_default_interval end end
To be overridden in subclasses .
1,903
def retry_in ( period ) return unless que_target if id = que_target . que_attrs [ :id ] values = [ period ] if e = que_target . que_error values << "#{e.class}: #{e.message}" . slice ( 0 , 500 ) << e . backtrace . join ( "\n" ) . slice ( 0 , 10000 ) else values << nil << nil end Que . execute :set_error , values << id end que_target . que_resolved = true end
Explicitly check for the job id in these helpers because it won t exist if we re running synchronously .
1,904
def push ( * metajobs ) Que . internal_log ( :job_buffer_push , self ) do { maximum_size : maximum_size , ids : metajobs . map ( & :id ) , current_queue : to_a , } end sync do return metajobs if _stopping? @array . concat ( metajobs ) . sort! priority_queues . reverse_each do | _ , pq | pq . waiting_count . times do job = _shift_job ( pq . priority ) break if job . nil? pq . push ( job ) end end overage = - _buffer_space pop ( overage ) if overage > 0 end end
Since we use a mutex which is not reentrant we have to be a little careful to not call a method that locks the mutex when we ve already locked it . So as a general rule public methods handle locking the mutex when necessary while private methods handle the actual underlying data changes . This lets us reuse those private methods without running into locking issues .
1,905
def ips_for ( name ) resolvers . each do | r | ips = r . getaddresses ( name ) return ips unless ips . nil? || ips . empty? end [ ] end
Get ips for given name
1,906
def mime_type ( type , value ) type = ".#{type}" unless type . to_s [ 0 ] == '.' :: Rack :: Mime :: MIME_TYPES [ type ] = value end
Add a new mime - type for a specific extension
1,907
def activate ( ext_name , options_hash = :: Middleman :: EMPTY_HASH , & block ) begin extension = :: Middleman :: Extensions . load ( ext_name ) rescue LoadError => e logger . debug "== Failed Activation `#{ext_name}` : #{e.message}" return end logger . debug "== Activating: #{ext_name}" if extension . supports_multiple_instances? @activated [ ext_name ] ||= { } key = "instance_#{@activated[ext_name].keys.length}" @activated [ ext_name ] [ key ] = extension . new ( @app , options_hash , & block ) elsif active? ( ext_name ) raise "#{ext_name} has already been activated and cannot be re-activated." else @activated [ ext_name ] = extension . new ( @app , options_hash , & block ) end end
Activate an extension optionally passing in options . This method is typically used from a project s config . rb .
1,908
def apply_cli_options config [ :cli_options ] . each do | k , v | setting = config . setting ( k . to_sym ) next unless setting v = setting . options [ :import ] . call ( v ) if setting . options [ :import ] config [ k . to_sym ] = v end end
Initialize the Middleman project
1,909
def prune_tilt_templates! mapping = :: Tilt . default_mapping mapping . lazy_map . each_key do | key | begin mapping [ key ] rescue LoadError , NameError end end mapping . lazy_map . clear end
Clean up missing Tilt exts
1,910
def extension copy_file 'extension/gitignore' , File . join ( name , '.gitignore' ) unless options [ :' ' ] template 'extension/Rakefile' , File . join ( name , 'Rakefile' ) template 'extension/gemspec' , File . join ( name , "#{name}.gemspec" ) template 'extension/Gemfile' , File . join ( name , 'Gemfile' ) template 'extension/lib/lib.rb' , File . join ( name , 'lib' , "#{name}.rb" ) template 'extension/lib/lib/extension.rb' , File . join ( name , 'lib' , name , 'extension.rb' ) template 'extension/features/support/env.rb' , File . join ( name , 'features' , 'support' , 'env.rb' ) empty_directory File . join ( name , 'fixtures' ) end
The extension task
1,911
def add_exposed_to_context ( context ) ( self . class . exposed_to_template || { } ) . each do | k , v | context . define_singleton_method ( k , & method ( v ) ) end end
Extensions are instantiated when they are activated .
1,912
def init require 'fileutils' require 'tmpdir' unless git_present? msg = 'You need to install the git command line tool to initialize a new project. ' msg << "For help installing git, please refer to GitHub's tutorial at https://help.github.com/articles/set-up-git" say msg , :red exit 1 end repo_path , repo_branch = if shortname? ( options [ :template ] ) require 'open-uri' require 'json' api = 'https://directory.middlemanapp.com/api' uri = :: URI . parse ( "#{api}/#{options[:template]}.json" ) begin data = :: JSON . parse ( uri . read ) is_local_dir = false data [ 'links' ] [ 'github' ] . split ( '#' ) rescue :: OpenURI :: HTTPError say "Template `#{options[:template]}` not found in Middleman Directory." say 'Did you mean to use a full `user/repo` path?' exit 1 end else repo_name , repo_branch = options [ :template ] . split ( '#' ) repo_path , is_local_dir = repository_path ( repo_name ) [ repo_path , repo_branch ] end begin dir = is_local_dir ? repo_path : clone_repository ( repo_path , repo_branch ) inside ( target ) do thorfile = File . join ( dir , 'Thorfile' ) if File . exist? ( thorfile ) :: Thor :: Util . load_thorfile ( thorfile ) invoke 'middleman:generator' else source_paths << dir directory dir , '.' , exclude_pattern : / \. \/ \. / end bundle_args = options [ :' ' ] ? " --path=#{options[:'bundle-path']}" : '' run ( "bundle install#{bundle_args}" ) unless ENV [ 'TEST' ] || options [ :' ' ] end ensure FileUtils . remove_entry ( dir ) if ! is_local_dir && File . directory? ( dir ) end end
The init task
1,913
def which ( executable ) if File . file? ( executable ) && File . executable? ( executable ) executable elsif ENV [ 'PATH' ] path = ENV [ 'PATH' ] . split ( File :: PATH_SEPARATOR ) . find do | p | abs_path = File . join ( p , executable ) File . file? ( abs_path ) && File . executable? ( abs_path ) end path && File . expand_path ( executable , path ) end end
Copied from Bundler
1,914
def build root = ENV [ 'MM_ROOT' ] || Dir . pwd raise Thor :: Error , 'Error: Could not find a Middleman project config, perhaps you are in the wrong folder?' unless File . exist? ( File . join ( root , 'config.rb' ) ) require 'middleman-core' require 'middleman-core/logger' require 'middleman-core/builder' require 'fileutils' verbose = options [ 'verbose' ] ? 0 : 1 instrument = options [ 'instrument' ] builder = nil cli_options = options :: Middleman :: Logger . singleton ( verbose , instrument ) :: Middleman :: Util . instrument 'builder.setup' do missing_and_changed = ! options [ 'only_changed' ] && options [ 'missing_and_changed' ] should_track_dependencies = options [ 'only_changed' ] || missing_and_changed || options [ 'track_dependencies' ] data_collection_depth = options [ 'data_collection_depth' ] @app = :: Middleman :: Application . new do config [ :mode ] = :build config [ :show_exceptions ] = false config [ :cli_options ] = cli_options . each_with_object ( { } ) do | ( k , v ) , sum | sum [ k ] = v end config [ :track_data_access ] = should_track_dependencies config [ :data_collection_depth ] = data_collection_depth end builder = Middleman :: Builder . new ( @app , glob : options [ 'glob' ] , dry_run : options [ 'dry_run' ] , clean : options [ 'clean' ] , parallel : options [ 'parallel' ] , only_changed : options [ 'only_changed' ] , missing_and_changed : missing_and_changed , track_dependencies : should_track_dependencies , visualize_graph : options [ 'visualize_graph' ] ) builder . thor = self builder . on_build_event ( & method ( :on_event ) ) end :: Middleman :: Util . instrument 'builder.run' do if builder . run! clean_directories! if options [ 'clean' ] puts 'Project built successfully.' else msg = 'There were errors during this build' msg << ', re-run with `middleman build --verbose` to see the full exception.' unless options [ 'verbose' ] shell . say msg , :red exit ( 1 ) end end end
Core build Thor command
1,915
def on_event ( event_type , target , extra = nil ) case event_type when :error say_status :error , target , :red shell . say extra , :red if options [ 'verbose' ] || options [ 'bail' ] raise 'Build error' if options [ 'bail' ] when :deleted say_status :remove , target , :green when :created say_status :create , target , :green when :identical say_status :identical , target , :blue when :skipped say_status :skipped , target , :blue when :updated say_status :updated , target , :yellow else say_status event_type , extra , :blue end end
Handles incoming events from the builder .
1,916
def clean_directories! all_build_files = File . join ( @app . config [ :build_dir ] , '**' , '*' ) empty_directories = Dir [ all_build_files ] . select do | d | File . directory? ( d ) end empty_directories . each do | d | remove_file d , force : true if Pathname ( d ) . children . empty? end end
Find empty directories in the build folder and remove them .
1,917
def process_request ( env , req , res ) start_time = Time . now request_path = URI . decode ( env [ 'PATH_INFO' ] . dup ) request_path . force_encoding ( 'UTF-8' ) if request_path . respond_to? :force_encoding request_path = :: Middleman :: Util . full_path ( request_path , @middleman ) full_request_path = File . join ( env [ 'SCRIPT_NAME' ] , request_path ) resource = @middleman . sitemap . by_destination_path ( request_path . gsub ( ' ' , '%20' ) ) return not_found ( res , full_request_path ) unless resource && ! resource . ignored? return send_file ( resource , env ) if resource . binary? || resource . static_file? res [ 'Content-Type' ] = resource . content_type || 'text/plain' begin res . write resource . render ( { } , rack : { request : req } ) res . status = 200 rescue Middleman :: TemplateRenderer :: TemplateNotFound => e res . write "Error: #{e.message}" res . status = 500 end logger . debug "== Finishing Request: #{resource.destination_path} (#{(Time.now - start_time).round(2)}s)" halt res . finish end
Core response method . We process the request check with the sitemap and return the correct file response or status message .
1,918
def not_found ( res , path ) path = :: Rack :: Utils . escape_html ( path ) res . status = 404 res . write "<html><head></head><body><h1>File Not Found</h1><p>#{path}</p></body></html>" res . finish end
Halt request and return 404
1,919
def send_file ( resource , env ) file = :: Rack :: File . new nil path = resource . file_descriptor [ :full_path ] if ! file . respond_to? ( :path= ) request = :: Rack :: Request . new ( env ) response = file . serving ( request , path ) else file . path = path response = file . serving ( env ) end status = response [ 0 ] response [ 1 ] [ 'Content-Encoding' ] = 'gzip' if %w[ .svgz .gz ] . include? ( resource . ext ) if ! ( 100 .. 199 ) . cover? ( status ) && ! [ 204 , 205 , 304 ] . include? ( status ) response [ 1 ] [ 'Content-Type' ] = resource . content_type || ( resource . binary? ? 'application/octet-stream' : 'text/plain' ) end halt response end
Immediately send static file
1,920
def server require 'middleman-core' require 'middleman-core/preview_server' unless ENV [ 'MM_ROOT' ] puts '== Could not find a Middleman project config.rb' exit end params = { debug : options [ 'verbose' ] , instrumenting : options [ 'instrument' ] , reload_paths : options [ 'reload_paths' ] , daemon : options [ 'daemon' ] } puts '== The Middleman is loading' :: Middleman :: PreviewServer . start ( params , options ) end
Start the server
1,921
def wrap_layout ( layout_name , & block ) buf_was = save_buffer layout_file = :: Middleman :: TemplateRenderer . locate_layout ( @app , layout_name , current_engine ) extension = File . extname ( layout_file [ :relative_path ] ) engine = extension [ 1 .. - 1 ] . to_sym self . current_engine = engine engine_was = current_engine content = '' begin content = capture_html ( & block ) if block_given? ensure restore_buffer ( buf_was ) end @vertices <<= :: Middleman :: Dependencies :: FileVertex . from_source_file ( @app , layout_file ) concat_safe_content render_file ( layout_file , @locs , @opts ) { content } ensure self . current_engine = engine_was end
Allow layouts to be wrapped in the contents of other layouts .
1,922
def render_file ( file , locs , opts , & block ) _render_with_all_renderers ( file [ :relative_path ] . to_s , locs , self , opts , & block ) end
Render a path with locs opts and contents block .
1,923
def glob_directory ( path ) results = :: Dir [ path ] return results unless RUBY_PLATFORM =~ / / results . map { | r | r . encode ( 'UTF-8' , 'UTF-8-MAC' ) } end
Glob a directory and try to keep path encoding consistent .
1,924
def create_instance ( res ) response = res . parsed_response raise_error ( response [ 'error' ] , res . code ) if response . nil? || response . key? ( 'error' ) begin class_name = response [ 'entity' ] . split ( '_' ) . collect ( & :capitalize ) . join klass = Razorpay . const_get class_name rescue NameError klass = Razorpay :: Entity end klass . new ( response ) end
Recursively builds entity instances out of all hashes in the response object
1,925
def decrypt ( attribute , encrypted_value ) encrypted_attributes [ attribute . to_sym ] [ :operation ] = :decrypting encrypted_attributes [ attribute . to_sym ] [ :value_present ] = self . class . not_empty? ( encrypted_value ) self . class . decrypt ( attribute , encrypted_value , evaluated_attr_encrypted_options_for ( attribute ) ) end
Decrypts a value for the attribute specified using options evaluated in the current object s scope
1,926
def encrypt ( attribute , value ) encrypted_attributes [ attribute . to_sym ] [ :operation ] = :encrypting encrypted_attributes [ attribute . to_sym ] [ :value_present ] = self . class . not_empty? ( value ) self . class . encrypt ( attribute , value , evaluated_attr_encrypted_options_for ( attribute ) ) end
Encrypts a value for the attribute specified using options evaluated in the current object s scope
1,927
def encrypted_attributes @encrypted_attributes ||= begin duplicated = { } self . class . encrypted_attributes . map { | key , value | duplicated [ key ] = value . dup } duplicated end end
Copies the class level hash of encrypted attributes with virtual attribute names as keys and their corresponding options as values to the instance
1,928
def colorize ( params ) return self if self . class . disable_colorization require_windows_libs scan_for_colors . inject ( self . class . new ) do | str , match | colors_from_params ( match , params ) defaults_colors ( match ) str << "\033[#{match[0]};#{match[1]};#{match[2]}m#{match[3]}\033[0m" end end
Change color of string
1,929
def colorized? scan_for_colors . inject ( [ ] ) do | colors , match | colors << match . tap ( & :pop ) end . flatten . compact . any? end
Return true if string is colorized
1,930
def colors_from_params ( match , params ) case params when Hash then colors_from_hash ( match , params ) when Symbol then color_from_symbol ( match , params ) end end
Set color from params
1,931
def colors_from_hash ( match , hash ) match [ 0 ] = mode ( hash [ :mode ] ) if mode ( hash [ :mode ] ) match [ 1 ] = color ( hash [ :color ] ) if color ( hash [ :color ] ) match [ 2 ] = background_color ( hash [ :background ] ) if background_color ( hash [ :background ] ) end
Set colors from params hash
1,932
def color_methods colors . each do | key | next if key == :default define_method key do colorize ( :color => key ) end define_method "on_#{key}" do colorize ( :background => key ) end end end
Generate color and on_color methods
1,933
def parse_user_code epilogue = @scanner . epilogue return unless epilogue . text epilogue . text . scan ( / \n \r \n \r \n \r \Z /m ) do label = canonical_label ( $~ [ 1 ] ) range = epilogue . slice ( $~ . begin ( 2 ) , $~ . end ( 2 ) ) add_user_code ( label , range ) end end
User Code Block
1,934
def consume! ( token ) return self if @error action = @state . action [ token ] || @state . defact case action when Shift @sstack . push ( @state ) @state = action . goto_state shifted ( token ) when Reduce reduce_by! ( action . rule ) consume! ( token ) when Accept done when Error @error = true error else raise "Illegal action type: #{action.class}" end self end
consuming a terminal may set off a series of reduces before the terminal is shifted
1,935
def path ( state , rule ) rule . symbols . each_with_object ( [ ] ) do | tok , path | goto = state . gotos [ tok ] path << goto state = goto . to_state end end
Sequence of state transitions which would be taken when starting from state then following the RHS of rule right to the end
1,936
def walk_graph ( bitmap , graph ) index = Array . new ( graph . size , nil ) traversed = Set . new graph . nodes do | node | next if traversed . include? ( node ) traverse ( node , traversed , index , [ ] , bitmap , graph ) end end
traverse a directed graph each entry in bitmap corresponds to a graph node after the traversal the bitmap for each node will be the union of its original value and ALL the values for all the nodes which are reachable from it
1,937
def detailed_transition_graph @dtgraph ||= each_with_object ( Graph :: Labeled . new ( size ) ) do | s , graph | s . gotos . each do | tok , goto | path = if tok . terminal? [ tok ] else actions_to_reach_reduce ( s . ident , tok ) end graph . add_vector ( s . ident , goto . to_state . ident , path ) end end . tap { | graph | graph . start = 0 } . freeze end
Like transition_graph but rather than vectors labeled with NTs we have vectors labeled with the shortest series of terminals and reduce operations which could take us through the same transition
1,938
def replace ( placeholder , actual ) raise 'wrong placeholder' if placeholder != @target @target . heads . delete ( ptrs [ 0 ] ) if @target @target = actual @target . heads << @ptrs [ 0 ] @symbols . map! { | s | s == placeholder ? actual : s } end
sometimes a Rule is instantiated before the target is actually known it may be given a placeholder target first which is later replaced with the real one
1,939
def expand @expand ||= Racc . set_closure ( @heads . dup ) do | ptr | if ( sym = ptr . symbol ) && sym . nonterminal? sym . heads end end . freeze end
If an instance of this NT comes next then what rules could we be starting?
1,940
def attachment_image_tag ( record , name , * args , fallback : nil , host : nil , prefix : nil , format : nil , ** options ) file = record && record . public_send ( name ) classes = [ "attachment" , ( record . class . model_name . singular if record ) , name , * options [ :class ] ] if file image_tag ( attachment_url ( record , name , * args , host : host , prefix : prefix , format : format ) , options . merge ( class : classes ) ) elsif fallback classes << "fallback" image_tag ( fallback , options . merge ( class : classes ) ) end end
Generates an image tag for the given attachment adding appropriate classes and optionally falling back to the given fallback image if there is no file attached .
1,941
def attachment_cache_field ( object_name , method , object : , ** options ) options [ :data ] ||= { } options [ :data ] [ :reference ] ||= SecureRandom . hex attacher_value = object . send ( "#{method}_data" ) hidden_options = { multiple : options [ :multiple ] , value : attacher_value . try ( :to_json ) , object : object , disabled : attacher_value . blank? , id : nil , data : { reference : options [ :data ] [ :reference ] } } hidden_options . merge! ( index : options [ :index ] ) if options . key? ( :index ) hidden_field ( object_name , method , hidden_options ) end
Generates a hidden form field which tracks the id of the file in the cache before it is permanently stored .
1,942
def accepts_attachments_for ( collection_name , collection_class : , accessor_prefix : , attachment : :file , append : false ) include MultipleAttachments . new ( collection_name , collection_class : collection_class , name : accessor_prefix , attachment : attachment , append : append ) end
Macro which generates accessors in pure Ruby classes for assigning multiple attachments at once . This is primarily useful together with multiple file uploads . There is also an Active Record version of this macro .
1,943
def download return io if io . is_a? ( Tempfile ) Tempfile . new ( id , binmode : true ) . tap do | tempfile | IO . copy_stream ( io , tempfile ) tempfile . rewind tempfile . fsync end end
Downloads the file to a Tempfile on disk and returns this tempfile .
1,944
def to_hash { 'status' => status . to_hash , 'headers' => headers , 'body' => serializable_body , 'http_version' => http_version } . tap do | hash | hash [ 'adapter_metadata' ] = adapter_metadata unless adapter_metadata . empty? end end
Builds a serializable hash from the response data .
1,945
def around_http_request ( * filters , & block ) unless VCR . fibers_available? raise Errors :: NotSupportedError . new "VCR::Configuration#around_http_request requires fibers, " + "which are not available on your ruby intepreter." end fibers = { } fiber_errors = { } hook_allowed , hook_declaration = false , caller . first before_http_request ( * filters ) do | request | hook_allowed = true start_new_fiber_for ( request , fibers , fiber_errors , hook_declaration , block ) end after_http_request ( lambda { hook_allowed } ) do | request , response | fiber = fibers . delete ( Thread . current ) resume_fiber ( fiber , fiber_errors , response , hook_declaration ) end end
Adds a callback that will be executed around each HTTP request .
1,946
def country country_code , definition , options = { } return unless Phony . config . load? ( country_code ) definition . with country_code , options Phony :: CountryCodes . instance . add country_code , definition end
Define a country s rules .
1,947
def fixed length , options = { } options [ :zero ] = true if options [ :zero ] . nil? NationalSplitters :: Fixed . instance_for length , options end
National matcher & splitters .
1,948
def add country_code , country country_code = country_code . to_s optimized_country_code_access = country_code . size @countries ||= { } @countries [ optimized_country_code_access ] ||= { } @countries [ optimized_country_code_access ] [ country_code ] = country end
Add the given country to the mapping under the given country code .
1,949
def split number country , cc , national_number = partial_split number _ , ndc , * local = country . split national_number [ cc , ndc , * local ] end
Splits this number into cc ndc and locally split number parts .
1,950
def format number , options = { } country , _ , national_number = partial_split number country . format national_number , options end
Format the number .
1,951
def plausible? number , hints = { } normalized = clean number return false unless ( 4 .. 16 ) === normalized . size country , cc , rest = partial_split normalized cc_needed = hints [ :cc ] return false if cc_needed && ! ( cc_needed === cc ) country . plausible? rest , hints rescue StandardError return false end
Is this number plausible?
1,952
def vanity? number country , _ , national = partial_split number country . vanity? national end
Is the given number a vanity number?
1,953
def partial_split number cc = '' 1 . upto ( 3 ) do | i | cc << number . slice! ( 0 .. 0 ) country = countries [ i ] [ cc ] return [ country , cc , number ] if country end end
Split off the country and the cc and also return the national number part .
1,954
def split national_number _ , trunk , ndc , * rest = internal_split national_number [ trunk , ndc , * rest ] end
A number is split with the code handlers as given in the initializer .
1,955
def format national_number , options = { } type = options [ :format ] || @format space = options [ :spaces ] || @space || @@default_space local_space = options [ :local_spaces ] || @local_space || space || @@default_local_space parentheses = options [ :parentheses ] parentheses = @parentheses || @@default_parentheses if parentheses . nil? use_trunk = options [ :trunk ] trunk , ndc , * local_pieces = split national_number local = format_local local_pieces , local_space format_cc_ndc trunk , ndc , local , type , space , parentheses , use_trunk end
Format the number given the national part of it .
1,956
def normalize national_number clean! national_number normalized = @codes . reduce national_number do | number , code | result = code . normalize number break result if result number end normalized end
Removes 0s from partially normalized numbers such as 410443643533 .
1,957
def plausible? rest , hints = { } local , _ , ndc , * rest = internal_split rest return false if ndc . nil? return false if ndc && ndc . empty? return false if @invalid_ndcs && @invalid_ndcs === ndc ndc_needed = hints [ :ndc ] return false if ndc_needed && ! ( ndc_needed === ndc ) return false unless local return local . plausible? rest , hints end
Tests for plausibility of this national number .
1,958
def merge! ( other ) criteria = other . to_criteria selector . merge! ( criteria . selector ) options . merge! ( criteria . options ) self . documents = criteria . documents . dup unless criteria . documents . empty? self . scoping_options = criteria . scoping_options self . inclusions = ( inclusions + criteria . inclusions ) . uniq self end
Merge the other criteria into this one .
1,959
def only ( * args ) return clone if args . flatten . empty? args = args . flatten if ( args & Fields :: IDS ) . empty? args . unshift ( :_id ) end if klass . hereditary? super ( * args . push ( :_type ) ) else super ( * args ) end end
Overriden to include _type in the fields .
1,960
def read ( value = nil ) clone . tap do | criteria | criteria . options . merge! ( read : value ) end end
Set the read preference for the criteria .
1,961
def respond_to? ( name , include_private = false ) super || klass . respond_to? ( name ) || CHECK . respond_to? ( name , include_private ) end
Returns true if criteria responds to the given method .
1,962
def check_for_missing_documents! ( result , ids ) if ( result . size < ids . size ) && Mongoid . raise_not_found_error raise Errors :: DocumentNotFound . new ( klass , ids , ids - result . map ( & :_id ) ) end end
Are documents in the query missing and are we configured to raise an error?
1,963
def initialize_copy ( other ) @inclusions = other . inclusions . dup @scoping_options = other . scoping_options @documents = other . documents . dup @context = nil super end
Clone or dup the current + Criteria + . This will return a new criteria with the selector options klass embedded options etc intact .
1,964
def type_selection klasses = klass . _types if klasses . size > 1 { _type : { "$in" => klass . _types } } else { _type : klass . _types [ 0 ] } end end
Get the selector for type selection .
1,965
def positionally ( selector , operations , processed = { } ) if selector . size == 1 || selector . values . any? { | val | val . nil? } return operations end keys = selector . keys . map { | m | m . sub ( '._id' , '' ) } - [ '_id' ] keys = keys . sort_by { | s | s . length * - 1 } process_operations ( keys , operations , processed ) end
Takes the provided selector and atomic operations and replaces the indexes of the embedded documents with the positional operator when needed .
1,966
def define_touchable! ( association ) name = association . name method_name = define_relation_touch_method ( name , association ) association . inverse_class . tap do | klass | klass . after_save method_name klass . after_destroy method_name klass . after_touch method_name end end
Add the association to the touchable associations if the touch option was provided .
1,967
def default_logger logger = Logger . new ( $stdout ) logger . level = Mongoid :: Config . log_level logger end
Gets the default Mongoid logger - stdout .
1,968
def process_localized_attributes ( klass , attrs ) klass . localized_fields . keys . each do | name | if value = attrs . delete ( name ) attrs [ "#{name}_translations" ] = value end end klass . embedded_relations . each do | _ , association | next unless attrs . present? && attrs [ association . key ] . present? if association . is_a? ( Association :: Embedded :: EmbedsMany ) attrs [ association . key ] . each do | attr | embedded_klass = attr . fetch ( '_type' , association . class_name ) . constantize process_localized_attributes ( embedded_klass , attr ) end else process_localized_attributes ( association . klass , attrs [ association . key ] ) end end end
When cloning if the document has localized fields we need to ensure they are properly processed in the clone .
1,969
def shard_key_selector selector = { } shard_key_fields . each do | field | selector [ field . to_s ] = new_record? ? send ( field ) : attribute_was ( field ) end selector end
Get the document selector with the defined shard keys .
1,970
def reload reloaded = _reload if Mongoid . raise_not_found_error && reloaded . empty? raise Errors :: DocumentNotFound . new ( self . class , _id , _id ) end @attributes = reloaded @attributes_before_type_cast = { } changed_attributes . clear reset_readonly apply_defaults reload_relations run_callbacks ( :find ) unless _find_callbacks . empty? run_callbacks ( :initialize ) unless _initialize_callbacks . empty? self end
Reloads the + Document + attributes from the database . If the document has not been saved then an error will get raised if the configuration option was set . This can reload root documents or embedded documents .
1,971
def reload_root_document { } . merge ( collection . find ( { _id : _id } , session : _session ) . read ( mode : :primary ) . first || { } ) end
Reload the root document .
1,972
def reload_embedded_document extract_embedded_attributes ( { } . merge ( collection ( _root ) . find ( _id : _root . _id ) . read ( mode : :primary ) . first ) ) end
Reload the embedded document .
1,973
def extract_embedded_attributes ( attributes ) atomic_position . split ( "." ) . inject ( attributes ) do | attrs , part | attrs = attrs [ part =~ / \d / ? part . to_i : part ] attrs end end
Extract only the desired embedded document from the attributes .
1,974
def attribute_present? ( name ) attribute = read_raw_attribute ( name ) ! attribute . blank? || attribute == false rescue ActiveModel :: MissingAttributeError false end
Determine if an attribute is present .
1,975
def read_attribute ( name ) field = fields [ name . to_s ] raw = read_raw_attribute ( name ) field ? field . demongoize ( raw ) : raw end
Read a value from the document attributes . If the value does not exist it will return nil .
1,976
def read_attribute_before_type_cast ( name ) attr = name . to_s if attributes_before_type_cast . key? ( attr ) attributes_before_type_cast [ attr ] else read_raw_attribute ( attr ) end end
Read a value from the attributes before type cast . If the value has not yet been assigned then this will return the attribute s existing value using read_raw_attribute .
1,977
def remove_attribute ( name ) as_writable_attribute! ( name ) do | access | _assigning do attribute_will_change! ( access ) delayed_atomic_unsets [ atomic_attribute_name ( access ) ] = [ ] unless new_record? attributes . delete ( access ) end end end
Remove a value from the + Document + attributes . If the value does not exist it will fail gracefully .
1,978
def write_attribute ( name , value ) access = database_field_name ( name ) if attribute_writable? ( access ) _assigning do validate_attribute_value ( access , value ) localized = fields [ access ] . try ( :localized? ) attributes_before_type_cast [ name . to_s ] = value typed_value = typed_value_for ( access , value ) unless attributes [ access ] == typed_value || attribute_changed? ( access ) attribute_will_change! ( access ) end if localized attributes [ access ] ||= { } attributes [ access ] . merge! ( typed_value ) else attributes [ access ] = typed_value end typed_value end end end
Write a single attribute to the document attribute hash . This will also fire the before and after update callbacks and perform any necessary typecasting .
1,979
def attribute_missing? ( name ) selection = __selected_fields return false unless selection field = fields [ name ] ( selection . values . first == 0 && selection_excluded? ( name , selection , field ) ) || ( selection . values . first == 1 && ! selection_included? ( name , selection , field ) ) end
Determine if the attribute is missing from the document due to loading it from the database with missing fields .
1,980
def typed_value_for ( key , value ) fields . key? ( key ) ? fields [ key ] . mongoize ( value ) : value . mongoize end
Return the typecasted value for a field .
1,981
def validate_attribute_value ( access , value ) return unless fields [ access ] && value validatable_types = [ Hash , Array ] if validatable_types . include? fields [ access ] . type unless value . is_a? fields [ access ] . type raise Mongoid :: Errors :: InvalidValue . new ( fields [ access ] . type , value . class ) end end end
Validates an attribute value . This provides validation checking if the value is valid for given a field . For now only Hash and Array fields are validated .
1,982
def build ( klass , attributes = nil ) attributes ||= { } type = attributes [ TYPE ] || attributes [ TYPE . to_sym ] if type && klass . _types . include? ( type ) type . constantize . new ( attributes ) else klass . new ( attributes ) end end
Builds a new + Document + from the supplied attributes .
1,983
def from_db ( klass , attributes = nil , criteria = nil , selected_fields = nil ) if criteria selected_fields ||= criteria . options [ :fields ] end type = ( attributes || { } ) [ TYPE ] if type . blank? obj = klass . instantiate ( attributes , selected_fields ) if criteria && criteria . association && criteria . parent_document obj . set_relation ( criteria . association . inverse , criteria . parent_document ) end obj else camelized = type . camelize begin constantized = camelized . constantize rescue NameError raise Errors :: UnknownModel . new ( camelized , type ) end if ! constantized . respond_to? ( :instantiate ) raise Errors :: UnknownModel . new ( camelized , type ) end constantized . instantiate ( attributes , selected_fields ) end end
Builds a new + Document + from the supplied attributes loaded from the database .
1,984
def add_atomic_pull ( document ) document . flagged_for_destroy = true ( delayed_atomic_pulls [ document . association_name . to_s ] ||= [ ] ) . push ( document ) end
Add the document as an atomic pull .
1,985
def add_atomic_unset ( document ) document . flagged_for_destroy = true ( delayed_atomic_unsets [ document . association_name . to_s ] ||= [ ] ) . push ( document ) end
Add an atomic unset for the document .
1,986
def atomic_updates ( _use_indexes = false ) process_flagged_destroys mods = Modifiers . new generate_atomic_updates ( mods , self ) _children . each do | child | child . process_flagged_destroys generate_atomic_updates ( mods , child ) end mods end
Get all the atomic updates that need to happen for the current + Document + . This includes all changes that need to happen in the entire hierarchy that exists below where the save call was made .
1,987
def atomic_pulls pulls = { } delayed_atomic_pulls . each_pair do | _ , docs | path = nil ids = docs . map do | doc | path ||= doc . flag_as_destroyed doc . _id end pulls [ path ] = { "_id" => { "$in" => ids } } and path = nil end pulls end
Get all the attributes that need to be pulled .
1,988
def atomic_unsets unsets = [ ] delayed_atomic_unsets . each_pair do | name , docs | path = nil docs . each do | doc | path ||= doc . flag_as_destroyed end unsets . push ( path || name ) end unsets end
Get all the attributes that need to be unset .
1,989
def generate_atomic_updates ( mods , doc ) mods . unset ( doc . atomic_unsets ) mods . pull ( doc . atomic_pulls ) mods . set ( doc . atomic_sets ) mods . set ( doc . delayed_atomic_sets ) mods . push ( doc . atomic_pushes ) mods . push ( doc . atomic_array_pushes ) mods . add_to_set ( doc . atomic_array_add_to_sets ) mods . pull_all ( doc . atomic_array_pulls ) end
Generates the atomic updates in the correct order .
1,990
def collection ( parent = nil ) parent ? parent . collection . with ( client_options ) : client [ collection_name . to_sym ] end
Initialize the persistence context object .
1,991
def client @client ||= ( client = Clients . with_name ( client_name ) client = client . use ( database_name ) if database_name_option client . with ( client_options ) ) end
Get the client for this persistence context .
1,992
def changes _changes = { } changed . each do | attr | change = attribute_change ( attr ) _changes [ attr ] = change if change end _changes . with_indifferent_access end
Get all the changes for the document .
1,993
def move_changes @previous_changes = changes Atomic :: UPDATES . each do | update | send ( update ) . clear end changed_attributes . clear end
Call this method after save so the changes can be properly switched .
1,994
def attribute_change ( attr ) attr = database_field_name ( attr ) [ changed_attributes [ attr ] , attributes [ attr ] ] if attribute_changed? ( attr ) end
Get the old and new value for the provided attribute .
1,995
def attribute_changed? ( attr ) attr = database_field_name ( attr ) return false unless changed_attributes . key? ( attr ) changed_attributes [ attr ] != attributes [ attr ] end
Determine if a specific attribute has changed .
1,996
def attribute_changed_from_default? ( attr ) field = fields [ attr ] return false unless field attributes [ attr ] != field . eval_default ( self ) end
Get whether or not the field has a different value from the default .
1,997
def attribute_was ( attr ) attr = database_field_name ( attr ) attribute_changed? ( attr ) ? changed_attributes [ attr ] : attributes [ attr ] end
Get the previous value for the attribute .
1,998
def attribute_will_change! ( attr ) unless changed_attributes . key? ( attr ) changed_attributes [ attr ] = read_raw_attribute ( attr ) . __deep_copy__ end end
Flag an attribute as going to change .
1,999
def reset_attribute! ( attr ) attr = database_field_name ( attr ) attributes [ attr ] = changed_attributes . delete ( attr ) if attribute_changed? ( attr ) end
Set the attribute back to its old value .