idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
11,800
def check_arguments arguments arguments . each_with_index do | argument , index | next if argument . is_a? Numeric next if argument . is_a? String next if argument . is_a? Symbol next if argument . is_a? Hash next if argument . is_a? NilClass next if argument . is_a? TrueClass next if argument . is_a? FalseClass raise ...
Ensures the arguments are primitives .
11,801
def find_route_for ( path , verb ) path = path [ 1 .. - 1 ] if path [ 0 ] == '/' route_id = verb + path route = routes [ route_id ] route = routes [ "#{verb}notfound" ] if route == nil return route end
Given a request will parse it s path to find what it the apropriate controller to respond it .
11,802
def hide ( name ) base_fields [ name ] = base_fields [ name ] . dup base_fields [ name ] . widget = Widgets :: HiddenInput . new end
Hide field named + name +
11,803
def text ( name , options = { } ) field name , CharField . new ( options . merge ( widget : Widgets :: Textarea . new ) ) end
Declare a + CharField + with text area widget
11,804
def password ( name , options = { } ) field name , CharField . new ( options . merge ( widget : Widgets :: PasswordInput . new ) ) end
Declare a + CharField + with password widget
11,805
def regex ( name , regexp , options = { } ) field name , RegexField . new ( regexp , options ) end
Declare a + RegexField +
11,806
def choice ( name , choices = [ ] , options = { } ) field name , ChoiceField . new ( choices , options ) end
Declare a + ChoiceField + with + choices +
11,807
def typed_choice ( name , choices = [ ] , options = { } ) field name , TypedChoiceField . new ( choices , options ) end
Declare a + TypedChoiceField + with + choices +
11,808
def multiple_choice ( name , choices = [ ] , options = { } ) field name , MultipleChoiceField . new ( choices , options ) end
Declare a + MultipleChoiceField + with + choices +
11,809
def radio_choice ( name , choices = [ ] , options = { } ) field name , ChoiceField . new ( choices , options . merge ( widget : Widgets :: RadioSelect . new ) ) end
Declare a + ChoiceField + using the + RadioSelect + widget
11,810
def checkbox_multiple_choice ( name , choices = [ ] , options = { } ) field name , MultipleChoiceField . new ( choices , options . merge ( widget : Widgets :: CheckboxSelectMultiple . new ) ) end
Declare a + MultipleChoiceField + with the + CheckboxSelectMultiple + widget
11,811
def save ( filename , path , params = { } ) payload = get! path , nil , params File . write filename , payload . response . body end
Save the response body to a file
11,812
def csv_node ( data ) arrays = data . keys . select { | key | data [ key ] . is_a? Array } arrays . empty? ? [ data ] : data [ arrays . first ] end
Determins which part of the data is best suited to be displayed as CSV .
11,813
def http_get ( path , extra = nil , params = { } ) payload = self . class . get path , params APICake :: Payload . new payload end
Make a call with HTTParty and return a payload object .
11,814
def normalize ( path , extra = nil , params = { } ) if extra . is_a? ( Hash ) and params . empty? params = extra extra = nil end path = "#{path}/#{extra}" if extra path = "/#{path}" unless path [ 0 ] == '/' query = default_query . merge params params [ :query ] = query unless query . empty? params = default_params . me...
Normalize the three input parameters
11,815
def describe_synonym ( schema_name , synonym_name ) select_first ( "SELECT table_owner, table_name FROM all_synonyms WHERE owner = :owner AND synonym_name = :synonym_name" , schema_name . to_s . upcase , synonym_name . to_s . upcase ) end
all_synonyms view is quite slow therefore this implementation is overriden in OCI connection with faster native OCI method
11,816
def read with_connection do | socket | reply = Protocol :: Reply . allocate data = read_data ( socket , 36 ) response = data . unpack ( REPLY_DECODE_STR ) reply . length , reply . request_id , reply . response_to , reply . op_code , reply . flags , reply . cursor_id , reply . offset , reply . count = response if reply ...
Initialize the connection .
11,817
def write ( operations ) buf = "" operations . each do | operation | operation . request_id = ( @request_id += 1 ) operation . serialize ( buf ) end with_connection do | socket | socket . write ( buf ) end end
Write to the connection .
11,818
def read_data ( socket , length ) data = socket . read ( length ) unless data raise Errors :: ConnectionFailure . new ( "Attempted to read #{length} bytes from the socket but nothing was returned." ) end if data . length < length data << read_data ( socket , length - data . length ) end data end
Read data from the socket until we get back the number of bytes that we are expecting .
11,819
def command ( database , cmd , options = { } ) read ( Protocol :: Command . new ( database , cmd , options ) ) end
Execute a command against a database .
11,820
def connection connection_acquired = false begin pool . with do | conn | connection_acquired = true yield ( conn ) end rescue Timeout :: Error , ConnectionPool :: PoolShuttingDownError => e if e . kind_of? ( ConnectionPool :: PoolShuttingDownError ) @pool = nil Connection :: Manager . delete_pool ( self ) raise Errors ...
Get the underlying connection for the node .
11,821
def ensure_connected ( & block ) unless ( conn = stack ( :connection ) ) . empty? return yield ( conn . first ) end begin connection do | conn | connect ( conn ) unless conn . alive? conn . apply_credentials ( @credentials ) stack ( :connection ) << conn yield ( conn ) end rescue Exception => e if e . kind_of? ( Connec...
Yields the block if a connection can be established retrying when a connection error is raised .
11,822
def get_more ( database , collection , cursor_id , limit ) read ( Protocol :: GetMore . new ( database , collection , cursor_id , limit ) ) end
Execute a get more operation on the node .
11,823
def insert ( database , collection , documents , concern , options = { } ) write ( Protocol :: Insert . new ( database , collection , documents , options ) , concern ) end
Get the hash identifier for the node .
11,824
def process ( operation , & callback ) if executing? ( :pipeline ) queue . push ( [ operation , callback ] ) else flush ( [ [ operation , callback ] ] ) end end
Processes the provided operation on this node and will execute the callback when the operation is sent to the database .
11,825
def query ( database , collection , selector , options = { } ) read ( Protocol :: Query . new ( database , collection , selector , options ) ) end
Execute a query on the node .
11,826
def refresh if address . resolve ( self ) begin @refreshed_at = Time . now configure ( command ( "admin" , ismaster : 1 ) ) if ! primary? && executing? ( :ensure_primary ) raise Errors :: ReplicaSetReconfigured . new ( "#{inspect} is no longer the primary node." , { } ) elsif ! messagable? down! end rescue Timeout :: E...
Refresh information about the node such as it s status in the replica set and it s known peers .
11,827
def remove ( database , collection , selector , concern , options = { } ) write ( Protocol :: Delete . new ( database , collection , selector , options ) , concern ) end
Execute a remove command for the provided selector .
11,828
def update ( database , collection , selector , change , concern , options = { } ) write ( Protocol :: Update . new ( database , collection , selector , change , options ) , concern ) end
Execute an update command for the provided selector .
11,829
def connect ( conn ) start = Time . now conn . connect @latency = Time . now - start @down_at = nil true end
Connect the node on the underlying connection .
11,830
def discover ( * nodes ) nodes . flatten . compact . each do | peer | node = Node . new ( peer , options ) node . credentials . merge! ( @credentials ) peers . push ( node ) unless peers . include? ( node ) end end
Discover the additional nodes .
11,831
def flush ( ops = queue ) operations , callbacks = ops . transpose logging ( operations ) do ensure_connected do | conn | conn . write ( operations ) replies = conn . receive_replies ( operations ) replies . zip ( callbacks ) . map do | reply , callback | callback ? callback [ reply ] : reply end . last end end ensure ...
Flush the node operations to the database .
11,832
def start @nodes . each ( & :start ) @worker = Thread . start do Thread . abort_on_exception = true catch ( :shutdown ) do loop do Moped . logger . debug "replica_set: waiting for next client" server , client = @manager . next_client if server Moped . logger . debug "replica_set: proxying incoming request to mongo" ser...
Start the mock replica set .
11,833
def initiate primary , * secondaries = @nodes . shuffle primary . promote secondaries . each ( & :demote ) return primary , secondaries end
Pick a node to be master and mark the rest as secondary
11,834
def nodes needs_refresh , available = seeds . partition do | node | refreshable? ( node ) end available . concat ( refresh ( needs_refresh ) ) available . reject { | node | node . down? } end
Returns the list of available nodes refreshing 1 ) any nodes which were down and ready to be checked again and 2 ) any nodes whose information is out of date . Arbiter nodes are not returned .
11,835
def refresh ( nodes_to_refresh = seeds ) refreshed_nodes = [ ] seen = { } refresh_node = -> ( node ) do unless node . address . resolved begin node . refresh rescue Errors :: ConnectionFailure end end unless seen [ node ] || ! node . address . resolved seen [ node ] = true seeds . push ( node ) unless seeds . include? ...
Refreshes information for each of the nodes provided . The node list defaults to the list of all known nodes .
11,836
def with_primary ( & block ) if node = nodes . find ( & :primary? ) begin node . ensure_primary do return yield ( node ) end rescue Errors :: ConnectionFailure , Errors :: ReplicaSetReconfigured end end raise Errors :: ConnectionFailure , "Could not connect to a primary node for replica set #{inspect}" end
Yields the replica set s primary node to the provided block . This method will retry the block in case of connection errors or replica set reconfiguration .
11,837
def with_secondary ( & block ) available_nodes = available_secondary_nodes while node = available_nodes . shift begin return yield ( node ) rescue Errors :: ConnectionFailure , Errors :: ReplicaSetReconfigured => e next end end raise Errors :: ConnectionFailure , "Could not connect to a secondary node for replica set #...
Yields a secondary node if available otherwise the primary node . This method will retry the block in case of connection errors .
11,838
def refreshable? ( node ) return false if node . arbiter? node . down? ? node . down_at < down_boundary : node . needs_refresh? ( refresh_boundary ) end
Is the provided node refreshable? This is in the case where the refresh boundary has passed or the node has been down longer than the down boundary .
11,839
def refresh_peers ( node , & block ) node . peers . each do | node | if node . address . resolved block . call ( node ) unless seeds . include? ( node ) peers . push ( node ) unless peers . include? ( node ) end end end
Refresh the peers based on the node s peers .
11,840
def each documents = load_docs documents . each { | doc | yield doc } while more? return kill if limited? && @limit <= 0 documents = get_more documents . each { | doc | yield doc } end end
Iterate over the results of the query .
11,841
def get_more with_retry ( session . cluster ) do reply = @node . get_more @database , @collection , @cursor_id , request_limit @limit -= reply . count if limited? @cursor_id = reply . cursor_id reply . documents end end
Get more documents from the database for the cursor . Executes a get more command .
11,842
def load_docs @options [ :flags ] |= [ :no_cursor_timeout ] if @options [ :no_timeout ] options = @options . clone options [ :limit ] = request_limit reply , @node = read_preference . with_node ( session . cluster ) do | node | [ node . query ( @database , @collection , @selector , query_options ( options ) ) , node ] ...
Load the documents from the database .
11,843
def options options_string , options = match [ 10 ] , { database : database } unless options_string . nil? options_string . split ( / \& / ) . each do | option_string | key , value = option_string . split ( / / ) if WRITE_OPTIONS . include? ( key ) options [ :write ] = { key . to_sym => cast ( value ) } elsif read = RE...
Get the options provided in the URI .
11,844
def to_hash config = { database : database , hosts : hosts } if username && password config . merge! ( username : username , password : password ) end config end
Get the uri as a Mongoid friendly configuration hash .
11,845
def command ( command ) read_preference . with_node ( cluster ) do | node | node . command ( name , command , query_options ( { } ) ) end end
Run + command + on the database .
11,846
def create ( key , options = { } ) spec = options . merge ( ns : namespace , key : key ) spec [ :name ] ||= key . to_a . join ( "_" ) database . session . with ( write : { w : 1 } ) do | _s | _s [ :" " ] . insert ( spec ) end end
Create an index unless it already exists .
11,847
def drop ( key = nil ) if key index = self [ key ] or return false name = index [ "name" ] else name = "*" end result = database . command deleteIndexes : collection_name , index : name result [ "ok" ] == 1 end
Drop an index or all indexes .
11,848
def new ( options = { } ) session = with ( options ) session . instance_variable_set ( :@cluster , cluster . dup ) if block_given? yield ( session ) else session end end
Initialize a new database session .
11,849
def with ( options = { } ) session = dup session . options . update ( options ) if block_given? yield ( session ) else session end end
Create a new session with + options + reusing existing connections .
11,850
def resolve ( node ) return @resolved if @resolved start = Time . now retries = 0 begin Timeout :: timeout ( @timeout * 10 ) do Resolv . each_address ( host ) do | ip | if ip =~ Resolv :: IPv4 :: Regex @ip ||= ip break end end raise Resolv :: ResolvError unless @ip end @resolved = "#{ip}:#{port}" rescue Timeout :: Erro...
Instantiate the new address .
11,851
def apply_credentials ( logins ) unless credentials == logins logouts = credentials . keys - logins . keys logouts . each do | database | logout ( database ) end logins . each do | database , ( username , password ) | unless credentials [ database ] == [ username , password ] login ( database , username , password ) en...
Apply authentication credentials .
11,852
def login ( database , username , password ) getnonce = Protocol :: Command . new ( database , getnonce : 1 ) self . write ( [ getnonce ] ) reply = self . receive_replies ( [ getnonce ] ) . first if getnonce . failure? ( reply ) return end result = getnonce . results ( reply ) authenticate = Protocol :: Commands :: Aut...
Login the user to the provided database with the supplied password .
11,853
def logout ( database ) command = Protocol :: Command . new ( database , logout : 1 ) self . write ( [ command ] ) reply = self . receive_replies ( [ command ] ) . first if command . failure? ( reply ) return end credentials . delete ( database ) end
Logout the user from the provided database .
11,854
def with_retry ( cluster , retries = cluster . max_retries , & block ) begin block . call rescue Errors :: ConnectionFailure , Errors :: PotentialReconfiguration => e raise e if e . is_a? ( Errors :: PotentialReconfiguration ) && ! ( e . message . include? ( "not master" ) || e . message . include? ( "Not primary" ) ) ...
Execute the provided block on the cluster and retry if the execution fails .
11,855
def drop begin session . with ( read : :primary ) . command ( drop : name ) rescue Moped :: Errors :: OperationFailure => e raise e unless e . ns_not_found? false end end
Drop the collection .
11,856
def rename ( to_name ) begin session . with ( database : "admin" , read : :primary ) . command ( renameCollection : "#{database.name}.#{name}" , to : "#{database.name}.#{to_name}" ) rescue Moped :: Errors :: OperationFailure => e raise e unless e . ns_not_exists? false end end
Rename the collection
11,857
def insert ( documents , flags = nil ) with_retry ( cluster ) do docs = documents . is_a? ( Array ) ? documents : [ documents ] cluster . with_primary do | node | node . insert ( database . name , name , docs , write_concern , flags : flags || [ ] ) end end end
Initialize the new collection .
11,858
def count ( limit = false ) command = { count : collection . name , query : selector } command . merge! ( skip : operation . skip , limit : operation . limit ) if limit result = collection . database . command ( command ) result [ "n" ] . to_i end
Get the count of matching documents in the query .
11,859
def distinct ( key ) result = collection . database . command ( distinct : collection . name , key : key . to_s , query : selector ) result [ "values" ] end
Get the distinct values in the collection for the provided key .
11,860
def explain explanation = operation . selector . dup hint = explanation [ "$hint" ] sort = explanation [ "$orderby" ] max_scan = explanation [ "$maxScan" ] explanation = { "$query" => selector , "$explain" => true , } explanation [ "$orderby" ] = sort if sort explanation [ "$hint" ] = hint if hint explanation [ "$maxSc...
Explain the current query .
11,861
def first reply = read_preference . with_node ( cluster ) do | node | node . query ( operation . database , operation . collection , operation . selector , query_options ( fields : operation . fields , flags : operation . flags , skip : operation . skip , limit : - 1 ) ) end reply . documents . first end
Get the first matching document .
11,862
def remove with_retry ( cluster ) do cluster . with_primary do | node | node . remove ( operation . database , operation . collection , operation . basic_selector , write_concern , flags : [ :remove_first ] ) end end end
Remove a single document matching the query s selector .
11,863
def update ( change , flags = nil ) with_retry ( cluster ) do cluster . with_primary do | node | node . update ( operation . database , operation . collection , operation . selector [ "$query" ] || operation . selector , change , write_concern , flags : flags ) end end end
Update a single document matching the query s selector .
11,864
def get ( value ) propagate = value [ :w ] || value [ "w" ] if propagate == 0 || propagate == - 1 Unverified . new else Propagate . new ( value ) end end
Get the corresponding write concern for the provided value . If the value is unverified we get that concern otherwise we get propagate .
11,865
def instrument ( runner , args = { } ) with ( the ( args ) << using_the ( runner ) ) raise ADBError , last_stdout unless last_stdout . empty? end
send instrumentation requests
11,866
def build_find_params ( options ) keyconditions = [ ] keyparameters = [ ] parameters = [ ] includes = [ ] joins = [ ] sql = @ast . to_sql ( self , definition ) do | notification , value | case notification when :keycondition then keyconditions << value when :keyparameter then keyparameters << value when :parameter then...
Initializes the instance by setting the relevant parameters Actually builds the find parameters hash that should be used in the search_for named scope .
11,867
def sql_operator ( operator , field ) raise ScopedSearch :: QueryNotSupported , "the operator '#{operator}' is not supported for field type '#{field.type}'" if ! field . virtual? and [ :like , :unlike ] . include? ( operator ) and ! field . textual? SQL_OPERATORS [ operator ] end
Return the SQL operator to use given an operator symbol and field definition .
11,868
def translate_value ( field , value ) translated_value = field . complete_value [ value . to_sym ] raise ScopedSearch :: QueryNotSupported , "'#{field.field}' should be one of '#{field.complete_value.keys.join(', ')}', but the query was '#{value}'" if translated_value . nil? translated_value end
Validate the key name is in the set and translate the value to the set value .
11,869
def sort ( field , as : nil , default : "ASC" , html_options : { } , url_options : params ) unless as id = field . to_s . downcase == "id" as = id ? field . to_s . upcase : field . to_s . humanize end ascend = "#{field} ASC" descend = "#{field} DESC" selected_sort = [ ascend , descend ] . find { | o | o == params [ :or...
Creates a link that alternates between ascending and descending .
11,870
def build_autocomplete_options is_query_valid node = last_node completion = complete_options ( node ) suggestions = [ ] suggestions += complete_keyword if completion . include? ( :keyword ) suggestions += LOGICAL_INFIX_OPERATORS if completion . include? ( :logical_op ) suggestions += LOGICAL_PREFIX_OPERATORS + NULL_PRE...
Initializes the instance by setting the relevant parameters Test the validity of the current query and suggest possible completion
11,871
def complete_options ( node ) return [ :keyword ] + [ :prefix_op ] if tokens . empty? return [ :keyword ] if last_token_is ( PREFIX_OPERATORS ) if is_left_hand ( node ) if ( tokens . size == 1 || last_token_is ( PREFIX_OPERATORS + LOGICAL_INFIX_OPERATORS ) || last_token_is ( PREFIX_OPERATORS + LOGICAL_INFIX_OPERATORS ,...
parse the query and return the complete options
11,872
def complete_keyword keywords = [ ] definition . fields . each do | f | next unless f [ 1 ] . complete_enabled if ( f [ 1 ] . key_field ) keywords += complete_key ( f [ 0 ] , f [ 1 ] , tokens . last ) else keywords << f [ 0 ] . to_s + ' ' end end keywords . sort end
suggest all searchable field names . in relations suggest only the long format relation . field .
11,873
def complete_key ( name , field , val ) return [ "#{name}." ] if ! val || ! val . is_a? ( String ) || ! ( val . include? ( '.' ) ) val = val . sub ( / \. / , '' ) connection = definition . klass . connection quoted_table = field . key_klass . connection . quote_table_name ( field . key_klass . table_name ) quoted_field...
this method completes the keys list in a key - value schema in the format table . keyName
11,874
def complete_date_value options = [ ] options << '"30 minutes ago"' options << '"1 hour ago"' options << '"2 hours ago"' options << 'Today' options << 'Yesterday' options << 'Tomorrow' options << 2 . days . ago . strftime ( '%A' ) options << 3 . days . ago . strftime ( '%A' ) options << 4 . days . ago . strftime ( '%A'...
date value completer
11,875
def complete_key_value ( field , token , val ) key_name = token . sub ( / \. / , "" ) key_klass = field . key_klass . where ( field . key_field => key_name ) . first raise ScopedSearch :: QueryNotSupported , "Field '#{key_name}' not recognized for searching!" if key_klass . nil? query = completer_scope ( field ) if fie...
complete values in a key - value schema
11,876
def complete_operator ( node ) definition . operator_by_field_name ( node . value ) . map { | o | o . end_with? ( ' ' ) ? o : "#{o} " } end
This method complete infix operators by field type
11,877
def scoped_search ( * definitions ) self . scoped_search_definition ||= ScopedSearch :: Definition . new ( self ) unless self . scoped_search_definition . klass == self self . scoped_search_definition = ScopedSearch :: Definition . new ( self ) end definitions . each do | definition | if definition [ :on ] . kind_of? (...
Export the scoped_search method fo defining the search options . This method will create a definition instance for the class if it does not yet exist or if a parent definition exists then it will create a new one inheriting it and use the object as block argument and return value .
11,878
def operator_by_field_name ( name ) field = field_by_name ( name ) return [ ] if field . nil? return field . operators if field . operators return [ '=' , '!=' , '>' , '<' , '<=' , '>=' , '~' , '!~' , '^' , '!^' ] if field . virtual? return [ '=' , '!=' ] if field . set? || field . uuid? return [ '=' , '>' , '<' , '<='...
this method is used by the syntax auto completer to suggest operators .
11,879
def default_fields_for ( value , operator = nil ) column_types = [ :virtual ] column_types += [ :string , :text ] if [ nil , :like , :unlike , :ne , :eq ] . include? ( operator ) column_types += [ :double , :float , :decimal ] if value =~ NUMERICAL_REGXP column_types += [ :integer ] if value =~ INTEGER_REGXP column_typ...
Returns a list of appropriate fields to search in given a search keyword and operator .
11,880
def parse_temporal ( value ) return Date . current if value =~ / \b \b /i return 1 . day . ago . to_date if value =~ / \b \b /i return 1 . day . from_now . to_date if value =~ / \b \b /i return ( eval ( $1 . strip . gsub ( / \s / , '.' ) . downcase ) ) . to_datetime if value =~ / \A \s \d \s \b \b \s \b \b \s \z /i ret...
Try to parse a string as a datetime . Supported formats are Today Yesterday Sunday 1 day ago 2 hours ago 3 months ago 4 weeks from now Jan 23 2004 And many more formats that are documented in Ruby DateTime API Doc .
11,881
def reflection_by_name ( klass , name ) return if name . nil? klass . reflections [ name . to_sym ] || klass . reflections [ name . to_s ] end
Returns a reflection for a given klass and name
11,882
def register_named_scope! @klass . define_singleton_method ( :search_for ) do | query = '' , options = { } | klass = self definition = klass . scoped_search_definition search_scope = klass . all find_options = ScopedSearch :: QueryBuilder . build_query ( definition , query || '' , options ) search_scope = search_scope ...
Registers the search_for named scope within the class that is used for searching .
11,883
def method_missing ( name , * args ) if @collections . include? ( name . to_s ) @query = build_collection_query_object ( name , @additional_params , * args ) return @query elsif name . to_s =~ / / type = $1 if @collections . include? ( type ) @save_operations << Operation . new ( "Add" , $1 , args [ 0 ] ) else super en...
Creates a new instance of the Service class
11,884
def delete_object ( obj ) type = obj . class . to_s if obj . respond_to? ( :__metadata ) && ! obj . send ( :__metadata ) . nil? @save_operations << Operation . new ( "Delete" , type , obj ) else raise OData :: NotSupportedError . new "You cannot delete a non-tracked entity" end end
Queues an object for deletion . To actually remove it from the server you must call save_changes as well .
11,885
def respond_to? ( method ) if @collections . include? ( method . to_s ) return true elsif method . to_s =~ / / type = $1 if @collections . include? ( type ) return true else super end elsif @function_imports . include? ( method . to_s ) return true else super end end
Overridden to identify methods handled by method_missing
11,886
def load_property ( obj , nav_prop ) raise NotSupportedError , "You cannot load a property on an entity that isn't tracked" if obj . send ( :__metadata ) . nil? raise ArgumentError , "'#{nav_prop}' is not a valid navigation property" unless obj . respond_to? ( nav_prop . to_sym ) raise ArgumentError , "'#{nav_prop}' is...
Lazy loads a navigation property on a model
11,887
def add_link ( parent , nav_prop , child ) raise NotSupportedError , "You cannot add a link on an entity that isn't tracked (#{parent.class})" if parent . send ( :__metadata ) . nil? raise ArgumentError , "'#{nav_prop}' is not a valid navigation property for #{parent.class}" unless parent . respond_to? ( nav_prop . to_...
Adds a child object to a parent object s collection
11,888
def build_collection_query_object ( name , additional_parameters , * args ) root = "/#{name.to_s}" if args . empty? elsif args . size == 1 if args . first . to_s =~ / \d / id_metadata = find_id_metadata ( name . to_s ) root << build_id_path ( args . first , id_metadata ) else root << "(#{args.first})" end else root << ...
Constructs a QueryBuilder instance for a collection using the arguments provided .
11,889
def build_collections_and_classes @classes = Hash . new @class_metadata = Hash . new complex_types = @edmx . xpath ( "//edm:ComplexType" , @ds_namespaces ) || [ ] complex_types . each do | c | name = qualify_class_name ( c [ 'Name' ] ) props = c . xpath ( ".//edm:Property" , @ds_namespaces ) methods = props . collect {...
Build the classes required by the metadata
11,890
def build_function_imports functions = @edmx . xpath ( "//edm:EntityContainer/edm:FunctionImport" , @ds_namespaces ) functions . each do | f | http_method_attribute = f . xpath ( "@m:HttpMethod" , @ds_namespaces ) . first is_side_effecting_attribute = f . xpath ( "@edm:IsSideEffecting" , @ds_namespaces ) . first http_m...
Parses the function imports and fills the
11,891
def convert_to_local_type ( edmx_type ) return edm_to_ruby_type ( edmx_type ) if edmx_type =~ / / klass_name = qualify_class_name ( edmx_type . split ( '.' ) . last ) klass_name . camelize . constantize end
Converts the EDMX model type to the local model type
11,892
def build_property_metadata ( props , keys = [ ] ) metadata = { } props . each do | property_element | prop_meta = PropertyMetadata . new ( property_element ) prop_meta . is_key = keys . include? ( prop_meta . name ) prop_meta . association = Association . new ( property_element , @edmx ) if prop_meta . nav_prop metada...
Builds the metadata need for each property for things like feed customizations and navigation properties
11,893
def handle_collection_result ( result ) results = build_classes_from_result ( result ) while partial? && @options [ :eager_partial ] results . concat handle_partial end results end
Handle parsing of OData Atom result and return an array of Entry classes
11,894
def handle_exception ( e ) raise e unless defined? ( e . response ) && e . response != nil code = e . response [ :status ] error = Nokogiri :: XML ( e . response [ :body ] ) message = if error . xpath ( "m:error/m:message" , @ds_namespaces ) . first error . xpath ( "m:error/m:message" , @ds_namespaces ) . first . conte...
Handles errors from the OData service
11,895
def collect_navigation_properties ( klass_name , element , doc ) nav_props = element . xpath ( ".//edm:NavigationProperty" , @ds_namespaces ) @class_metadata [ klass_name ] . merge! ( build_property_metadata ( nav_props ) ) nav_props . collect { | p | p [ 'Name' ] } end
Similar to + collect_properties + but handles the navigation properties
11,896
def build_classes_from_result ( result ) doc = Nokogiri :: XML ( result ) is_links = doc . at_xpath ( "/ds:links" , @ds_namespaces ) return parse_link_results ( doc ) if is_links entries = doc . xpath ( "//atom:entry[not(ancestor::atom:entry)]" , @ds_namespaces ) extract_partial ( doc ) results = [ ] entries . each do ...
Helper to loop through a result and create an instance for each entity in the results
11,897
def entry_to_class ( entry ) klass_name = entry . xpath ( "./atom:category/@term" , @ds_namespaces ) . to_s . split ( '.' ) [ - 1 ] if klass_name . nil? title = entry . xpath ( "./atom:title" , @ds_namespaces ) . first return nil if title . nil? klass_name = title . content . to_s end return nil if klass_name . nil? pr...
Converts an XML Entry into a class
11,898
def extract_partial ( doc ) next_links = doc . xpath ( '//atom:link[@rel="next"]' , @ds_namespaces ) @has_partial = next_links . any? if @has_partial uri = Addressable :: URI . parse ( next_links [ 0 ] [ 'href' ] ) uri . query_values = uri . query_values . merge @additional_params unless @additional_params . empty? @ne...
Tests for and extracts the next href of a partial
11,899
def parse_link_results ( doc ) uris = doc . xpath ( "/ds:links/ds:uri" , @ds_namespaces ) results = [ ] uris . each do | uri_el | link = uri_el . content results << URI . parse ( link ) end results end
Handle link results