Input: Generates redis key for storing object * will produce something like : your_class : key : field_value1 : field_value2 ... ( depending on your redis_key setting ) [CODESPLIT] def generate_key args = { } , key = "key" #normalize input hash of arguments args = HashWithIndifferentAccess . new ( args ) out = "#{self.name.to_s.underscore.to_sym}:#{key}" redis_key_config . each do | key | out += add_item_to_redis_key args , key end out end


Input: Generates redis key for storing indexes for dynamic aliases will produce something like : your_class : dynamic : name_of_your_dynami_alias : field_value2 : field_value1 ... ( field values are sorted by fields order ) * dynamic_alias_name ( Symbol ) - name of your dynamic alias * args ( Hash ) - arguments of your model * field_order ( Array of symbols ) - order of fields ( ex . [ : field2 : field1 ] ) * field_args ( Hash ) - hash of values for aliasing ( ex . { : field1 = > field_value1 : field2 = > field_value2 } ) [CODESPLIT] def generate_alias_key alias_name , args = { } #check if asked dynamic alias exists raise ArgumentError , "Unknown dynamic alias: '#{alias_name}', use: #{redis_alias_config.keys.join(", ")} " unless redis_alias_config . has_key? ( alias_name . to_sym ) #normalize input hash of arguments args = HashWithIndifferentAccess . new ( args ) # prepare class name + dynamic + alias name out = "#{self.name.to_s.underscore.to_sym}:alias:#{alias_name}" #get config  config = redis_alias_config [ alias_name . to_sym ] # use all specified keys config [ :main_fields ] . each do | key | out += add_item_to_redis_key args , key end #is alias dynamic? if config [ :order_field ] && config [ :args_field ] #check if input arguments has order field if args . has_key? ( config [ :order_field ] ) && args [ config [ :order_field ] ] && args . has_key? ( config [ :args_field ] ) && args [ config [ :args_field ] ] #use filed order from defined field in args args [ config [ :order_field ] ] . each do | key | out += add_item_to_redis_key args [ config [ :args_field ] ] , key end else # use global search out += ":*" end end out end


Input: Check if key by arguments exists in db [CODESPLIT] def exists? args = { } RedisModelExtension :: Database . redis . exists ( self . name . constantize . generate_key ( args ) ) end


Input: Check if key by alias name and arguments exists in db [CODESPLIT] def alias_exists? alias_name , args = { } RedisModelExtension :: Database . redis . exists ( self . name . constantize . generate_alias_key ( alias_name , args ) ) end


Input: return one item of redis key ( will decide to input value or to add * for search ) [CODESPLIT] def add_item_to_redis_key args , key if args . has_key? ( key ) && ! args [ key ] . nil? key = ":#{args[key]}" key = key . mb_chars . downcase if redis_key_normalize_conf . include? ( :downcase ) key = ActiveSupport :: Inflector :: transliterate ( key ) if redis_key_normalize_conf . include? ( :transliterate ) key else ":*" end end


Input: Validates if key by arguments is valid ( all needed fields are not nil! ) [CODESPLIT] def valid_key? args = { } #normalize input hash of arguments args = HashWithIndifferentAccess . new ( args ) redis_key_config . each do | key | return false unless valid_item_for_redis_key? args , key end return true end


Input: Validates if key by alias name and arguments is valid ( all needed fields are not nil! ) [CODESPLIT] def valid_alias_key? alias_name , args = { } raise ArgumentError , "Unknown dynamic alias, use: #{redis_alias_config.keys.join(", ")}" unless redis_alias_config . has_key? ( alias_name . to_sym ) #normalize input hash of arguments args = HashWithIndifferentAccess . new ( args ) config = redis_alias_config [ alias_name . to_sym ] # use all specified keys config [ :main_fields ] . each do | key | return false unless valid_item_for_redis_key? args , key end # is dynamic alias? if config [ :order_field ] && config [ :args_field ] #check if input arguments has order field if args . has_key? ( config [ :order_field ] ) && args [ config [ :order_field ] ] && args . has_key? ( config [ :args_field ] ) && args [ config [ :args_field ] ] #use filed order from defined field in args args [ config [ :order_field ] ] . each do | key | return false unless valid_item_for_redis_key? args [ config [ :args_field ] ] , key end else return false end end return true end


Input: validate one item of redis key [CODESPLIT] def valid_item_for_redis_key? args , key ( args . has_key? ( key ) && ! args [ key ] . nil? ) || redis_fields_config [ key ] == :autoincrement end


Input: look for bad cofiguration in redis key and raise argument error [CODESPLIT] def validate_redis_key valid_fields = redis_fields_config . select { | k , v | v != :array && v != :hash } . keys bad_fields = redis_key_config - valid_fields raise ArgumentError , "Sorry, but you cannot use as redis key [nonexisting | array | hash] fields: [#{bad_fields.join(",")}], availible are: #{valid_fields.join(", ")}" unless bad_fields . size == 0 end


Input: take all arguments and send them out [CODESPLIT] def to_arg redis_fields_config . inject ( { } ) do | args , ( key , type ) | args [ key ] = self . send ( key ) args end end


Input: FIND METHODS [CODESPLIT] def find ( args = { } ) # when argument is integer - search by id args = { id : args } if args . is_a? ( Integer ) #normalize input hash of arguments args = HashWithIndifferentAccess . new ( args ) out = [ ] klass = self . name . constantize search_key = klass . generate_key ( args ) #is key specified directly? -> no needs of looking for other keys! -> faster unless search_key =~ / \* / out << klass . new_by_key ( search_key ) if klass . exists? ( args ) else RedisModelExtension :: Database . redis . keys ( search_key ) . each do | key | out << klass . new_by_key ( key ) end end out end


Input: Find method for searching in redis [CODESPLIT] def find_by_alias ( alias_name , args = { } ) #check if asked dynamic alias exists raise ArgumentError , "Unknown dynamic alias: '#{alias_name}', use: #{redis_alias_config.keys.join(", ")} " unless redis_alias_config . has_key? ( alias_name . to_sym ) #normalize input hash of arguments args = HashWithIndifferentAccess . new ( args ) out = [ ] klass = self . name . constantize search_key = klass . generate_alias_key ( alias_name , args ) #is key specified directly? -> no needs of looking for other keys! -> faster unless search_key =~ / \* / out = klass . get_by_alias ( alias_name , args ) if klass . alias_exists? ( alias_name , args ) else RedisModelExtension :: Database . redis . keys ( search_key ) . each do | key | out << klass . get_by_alias_key ( key ) end end out . flatten end


Input: GET BY ARGUMENTS [CODESPLIT] def get ( args = { } ) # when argument is integer - search by id args = { id : args } if args . is_a? ( Integer ) #normalize input hash of arguments args = HashWithIndifferentAccess . new ( args ) klass = self . name . constantize if klass . valid_key? ( args ) && klass . exists? ( args ) klass . new_by_key ( klass . generate_key ( args ) ) else nil end end


Input: GET BY REDIS KEYS [CODESPLIT] def get_by_alias ( alias_name , args = { } ) #check if asked dynamic alias exists raise ArgumentError , "Unknown dynamic alias: '#{alias_name}', use: #{redis_alias_config.keys.join(", ")} " unless redis_alias_config . has_key? ( alias_name . to_sym ) #normalize input hash of arguments args = HashWithIndifferentAccess . new ( args ) klass = self . name . constantize if klass . valid_alias_key? ( alias_name , args ) && klass . alias_exists? ( alias_name , args ) out = [ ] RedisModelExtension :: Database . redis . smembers ( klass . generate_alias_key ( alias_name , args ) ) . each do | key | item = klass . new_by_key ( key ) out << item if item end return out end nil end


Input: GET BY REDIS KEYS [CODESPLIT] def get_by_redis_key ( redis_key ) if redis_key . is_a? ( String ) klass = self . name . constantize klass . new_by_key ( redis_key ) else nil end end


Input: fastest method to get object from redis by getting it by alias and arguments [CODESPLIT] def get_by_alias_key ( alias_key ) klass = self . name . constantize if RedisModelExtension :: Database . redis . exists ( alias_key ) out = [ ] RedisModelExtension :: Database . redis . smembers ( alias_key ) . each do | key | item = klass . new_by_key ( key ) out << item if item end return out end nil end


Input: CREATE NEW OBJECT BY HASH VALUES [CODESPLIT] def new_by_key ( key ) args = RedisModelExtension :: Database . redis . hgetall ( key ) return nil unless args && args . any? args . symbolize_keys! new_instance = new ( args ) new_instance . store_keys return new_instance end


Input: choose right type of value and then transform it for redis [CODESPLIT] def value_to_redis name , value if redis_fields_config . has_key? ( name ) value_transform value , redis_fields_config [ name ] else value end end


Input: convert value for valid format which can be saved in redis [CODESPLIT] def value_transform value , type return nil if value . nil? || value . to_s . size == 0 case type when :integer then value . to_i when :autoincrement then value . to_i when :string then value . to_s when :float then value . to_f when :bool then value . to_s when :symbol then value . to_s when :marshal then Marshal . dump ( value ) when :array then Yajl :: Encoder . encode ( value ) when :hash then Yajl :: Encoder . encode ( value ) when :time then Time . parse ( value . to_s ) . strftime ( "%Y.%m.%d %H:%M:%S" ) when :date then Date . parse ( value . to_s ) . strftime ( "%Y-%m-%d" ) else value end end


Input: convert value from redis into valid format in ruby [CODESPLIT] def value_parse value , type return nil if value . nil? || value . to_s . size == 0 case type when :integer then value . to_i when :autoincrement then value . to_i when :string then value . to_s when :float then value . to_f when :bool then value . to_s . to_bool when :symbol then value . to_s . to_sym when :marshal then value . is_a? ( String ) ? Marshal . load ( value ) : value when :array then value . is_a? ( String ) ? Yajl :: Parser . parse ( value ) : value when :hash then value . is_a? ( String ) ? Hashr . new ( Yajl :: Parser . parse ( value ) ) : Hashr . new ( value ) when :time then value . is_a? ( String ) ? Time . parse ( value ) : value when :date then value . is_a? ( String ) ? Date . parse ( value ) : value else value end end


Input: save method - save all attributes ( fields ) and create aliases [CODESPLIT] def save perform = lambda do # can be saved into redis? if valid? #autoicrement id self . send ( "id=" , increment_id ) if redis_key_config . include? ( :id ) && ! self . id? #generate key (possibly new) generated_key = redis_key #take care about renaming saved hash in redis (if key changed) if redis_old_keys [ :key ] && redis_old_keys [ :key ] != generated_key && RedisModelExtension :: Database . redis . exists ( redis_old_keys [ :key ] ) RedisModelExtension :: Database . redis . rename ( redis_old_keys [ :key ] , generated_key ) end #ignore nil values for save  args = self . class . redis_save_fields_with_nil_conf ? to_arg : to_arg . reject { | k , v | v . nil? } #perform save to redis hash RedisModelExtension :: Database . redis . hmset ( generated_key , args . inject ( [ ] ) { | arr , kv | arr + [ kv [ 0 ] , value_to_redis ( kv [ 0 ] , kv [ 1 ] ) ] } ) # destroy aliases destroy_aliases! create_aliases #after save make sure instance remember old key to know if it needs to be ranamed store_keys end end run_callbacks :save do unless exists? run_callbacks :create do perform . ( ) end else perform . ( ) end end unless errors . any? return self else return false end end


Input: create aliases ( create key value [ STRING ] key is alias redis key and value is redis key ) [CODESPLIT] def create_aliases main_key = redis_key redis_alias_config . each do | alias_name , fields | RedisModelExtension :: Database . redis . sadd ( redis_alias_key ( alias_name ) , main_key ) if valid_alias_key? alias_name end end


Input: update multiple attrubutes at once [CODESPLIT] def update args args . each do | key , value | method = "#{key}=" . to_sym if self . respond_to? method self . send ( method , value ) end end end


Input: remove all aliases [CODESPLIT] def destroy_aliases! #do it only if it is existing object! if redis_old_keys [ :aliases ] . size > 0 redis_old_keys [ :aliases ] . each do | alias_key | RedisModelExtension :: Database . redis . srem alias_key , redis_old_keys [ :key ] #delete alias with 0 keys RedisModelExtension :: Database . redis . del ( alias_key ) if RedisModelExtension :: Database . redis . scard ( alias_key ) . to_i == 0 end end end


Input: Add entry to Apple Keychain [CODESPLIT] def add ( username , token ) Firim :: AccountManager . new ( user : username , token : token ) . add_to_keychain end


Input: Checks the response code for common errors . Returns parsed response for successful requests . [CODESPLIT] def validate ( response ) error_klass = case response . code when 400 then Error :: BadRequest when 401 then Error :: Unauthorized when 403 then Error :: Forbidden when 404 then Error :: NotFound when 405 then Error :: MethodNotAllowed when 409 then Error :: Conflict when 422 then Error :: Unprocessable when 500 then Error :: InternalServerError when 502 then Error :: BadGateway when 503 then Error :: ServiceUnavailable end fail error_klass . new ( response ) if error_klass parsed = response . parsed_response parsed . client = self if parsed . respond_to? ( :client= ) parsed . parse_headers! ( response . headers ) if parsed . respond_to? ( :parse_headers! ) parsed end


Input: Returns an array of nsqd addresses If there s an error return nil [CODESPLIT] def get_nsqds ( lookupd , topic = nil ) uri_scheme = 'http://' unless lookupd . match ( %r( ) ) uri = URI . parse ( "#{uri_scheme}#{lookupd}" ) uri . query = "ts=#{Time.now.to_i}" if topic uri . path = '/lookup' uri . query += "&topic=#{URI.escape(topic)}" else uri . path = '/nodes' end begin body = Net :: HTTP . get ( uri ) data = JSON . parse ( body ) producers = data [ 'producers' ] || # v1.0.0-compat ( data [ 'data' ] && data [ 'data' ] [ 'producers' ] ) if producers producers . map do | producer | "#{producer['broadcast_address']}:#{producer['tcp_port']}" end else [ ] end rescue Exception => e error "Error during discovery for #{lookupd}: #{e}" nil end end


Input: discovers nsqds from an nsqlookupd repeatedly [CODESPLIT] def discover_repeatedly ( opts = { } ) @discovery_thread = Thread . new do @discovery = Discovery . new ( opts [ :nsqlookupds ] ) loop do begin nsqds = nsqds_from_lookupd ( opts [ :topic ] ) drop_and_add_connections ( nsqds ) rescue DiscoveryException # We can't connect to any nsqlookupds. That's okay, we'll just # leave our current nsqd connections alone and try again later. warn 'Could not connect to any nsqlookupd instances in discovery loop' end sleep opts [ :interval ] end end @discovery_thread . abort_on_exception = true end


Input: Retry the supplied block with exponential backoff . [CODESPLIT] def with_retries ( & block ) base_sleep_seconds = 0.5 max_sleep_seconds = 300 # 5 minutes # Let's do this thing attempts = 0 begin attempts += 1 return block . call ( attempts ) rescue Errno :: ECONNREFUSED , Errno :: ECONNRESET , Errno :: EHOSTUNREACH , Errno :: ENETDOWN , Errno :: ENETUNREACH , Errno :: ETIMEDOUT , Timeout :: Error => ex raise ex if attempts >= 100 # The sleep time is an exponentially-increasing function of base_sleep_seconds. # But, it never exceeds max_sleep_seconds. sleep_seconds = [ base_sleep_seconds * ( 2 ** ( attempts - 1 ) ) , max_sleep_seconds ] . min # Randomize to a random value in the range sleep_seconds/2 .. sleep_seconds sleep_seconds = sleep_seconds * ( 0.5 * ( 1 + rand ( ) ) ) # But never sleep less than base_sleep_seconds sleep_seconds = [ base_sleep_seconds , sleep_seconds ] . max warn "Failed to connect: #{ex}. Retrying in #{sleep_seconds.round(1)} seconds." snooze ( sleep_seconds ) retry end end


Input: @param [ Hash ] args - all possible parameters - @option [ String ] controller_class_name - @option [ Class ] controller_class - @option [ String ] verb - @option [ String ] operation_name - @option [ String ] model_name - @option [ Class ] model_class - @option [ Hash ] options PostsController = > PostOperations :: Verb [CODESPLIT] def operation_class @operation_class ||= begin found_namespace = ensure_namespace! ( operation_namespace ) operation = namespaced_operation_name . split ( found_namespace . name ) . last qualified_name = found_namespace ? found_namespace . name + operation : namespaced_operation_name ensure_operation_class! ( qualified_name ) end end


Input: In order of most specific to least specific : - { action } _ { model_name } _params - { action } _params - { model_key } _params - resource_params - params [CODESPLIT] def params_for_action return { } if action_name == 'destroy' key = _options [ :model_params_key ] # model_class should be a class klass = _options [ :model_class ] model_key = if key . present? key elsif klass klass . name . underscore else _lookup . model_name . underscore end params_lookups = [ # e.g.: create_post_params "#{action_name}_#{model_key}_params" , # generic for action "#{action_name}_params" , # e.g.: post_params "#{model_key}_params" , # most generic 'resource_params' ] lookup_params_for_action ( params_lookups ) end


Input: parse_int [CODESPLIT] def parse_attributes ( e ) throw Exception . new ( "No name attribute found for : #{e.inspect}" ) unless name = e . attributes [ "name" ] throw Exception . new ( "Cannot parse attribute 'min' for: #{e.inspect}" ) unless min = parse_int ( e . attributes [ "min" ] ) throw Exception . new ( "Cannot parse attribute 'max' for: #{e.inspect}" ) unless max = parse_int ( e . attributes [ "max" ] ) throw Exception . new ( "Cannot parse attribute 'type' for: #{e.inspect}" ) unless type = parse_type ( e . attributes [ "type" ] ) throw Exception . new ( "Cannot parse attribute 'required' for: #{e.inspect}" ) if ( required = parse_boolean ( e . attributes [ "required" ] ) ) . nil? validation = e . attributes [ "validation" ] min = 1 if required and min < 1 max = 999999 if max == 0 return name , min , max , type , required , validation end


Input:
parse_attributes [CODESPLIT] def parse_field ( e ) name , min , max , type , required , validation = parse_attributes ( e ) # FIXME - for compatibility with d12 - constants are stored in attribute 'type' and are enclosed in
 # double quotes
 const_field = e . attributes [ "const" ] if ( const_field ) type = "\"#{const_field}\"" end Field . new ( name , type , required , min , max , validation ) end


Input: parse_field [CODESPLIT] def parse_table ( e ) name , min , max , type , required , validation = parse_attributes ( e ) content = e . find ( "Entry" ) . inject ( { } ) { | t , entry | t [ entry . attributes [ "name" ] ] = entry . attributes [ "value" ] t } Table . new ( name , content ) end


Input:
Prints a tree - like representation of the element [CODESPLIT] def show ( ind = '' ) count = 0 self . to_a . each { | i | #puts "#{ind}#{i.name} #{i.object_id} #{i.super.object_id} [#{count}]: #{i.parsed_str} #{i.super.class}"
 puts "#{ind}#{i.name} [#{count}]: #{i.to_s.sub(/^(.{30})(.*?)(.{30})$/, '\1...\3')}" # Force parsing a segment
 if i . kind_of? ( X12 :: Segment ) && i . nodes [ 0 ] i . find_field ( i . nodes [ 0 ] . name ) end i . nodes . each { | j | case when j . kind_of? ( X12 :: Base ) then j . show ( ind + '  ' ) when j . kind_of? ( X12 :: Field ) then puts "#{ind+'  '}#{j.name} -> '#{j.to_s}'" end } count += 1 } end


Input:
Try to parse the current element one more time if required . Returns the rest of the string or the same string if no more repeats are found or required . [CODESPLIT] def do_repeats ( s ) if self . repeats . end > 1 possible_repeat = self . dup p_s = possible_repeat . parse ( s ) if p_s s = p_s self . next_repeat = possible_repeat end # if parsed
 end # more repeats
 s end


Input:
Make a deep copy of the element dup Recursively find a sub - element which also has to be of type Base . [CODESPLIT] def find ( e ) #puts "Finding [#{e}] in #{self.class} #{name}"
 case self when X12 :: Loop # Breadth first
 res = nodes . find { | i | e == i . name } return res if res # Depth now
 nodes . each { | i | res = i . find ( e ) if i . kind_of? ( X12 :: Loop ) return res unless res . nil? or EMPTY == res # otherwise keep looping
 } when X12 :: Segment return find_field ( e ) . to_s end # case
 return EMPTY end


Input: Present self and all repeats as an array with self being #0 [CODESPLIT] def to_a res = [ self ] nr = self . next_repeat while nr do res << nr nr = nr . next_repeat end res end


Input:
The main method implementing Ruby - like access methods for nested elements [CODESPLIT] def method_missing ( meth , * args , & block ) str = meth . id2name str = str [ 1 .. str . length ] if str =~ / \d / # to avoid pure number names like 270, 997, etc.
 #puts "Missing #{str}"
 if str =~ / / # Assignment
 str . chop! #puts str
 case self when X12 :: Segment res = find_field ( str ) throw Exception . new ( "No field '#{str}' in segment '#{self.name}'" ) if EMPTY == res res . content = args [ 0 ] . to_s #puts res.inspect
 else throw Exception . new ( "Illegal assignment to #{meth} of #{self.class}" ) end # case
 else # Retrieval
 res = find ( str ) yield res if block_given? res end # if assignment
 end


Input:
Adds a repeat to a segment or loop . Returns a new segment / loop or self if empty . [CODESPLIT] def repeat res = if self . has_content? # Do not repeat an empty segment
 last_repeat = self . to_a [ - 1 ] last_repeat . next_repeat = last_repeat . dup else self end yield res if block_given? res end


Input:
Parses this segment out of a string puts the match into value returns the rest of the string - nil if cannot parse [CODESPLIT] def parse ( str ) s = str #puts "Parsing segment #{name} from #{s} with regexp [#{regexp.source}]"
 m = regexp . match ( s ) #puts "Matched #{m ? m[0] : 'nothing'}"
 return nil unless m s = m . post_match self . parsed_str = m [ 0 ] s = do_repeats ( s ) #puts "Parsed segment "+self.inspect
 return s end


Input:
parse Render all components of this segment as string suitable for EDI [CODESPLIT] def render self . to_a . inject ( '' ) { | repeat_str , i | if i . repeats . begin < 1 and ! i . has_content? # Skip optional empty segments
 repeat_str else # Have to render no matter how empty
 repeat_str += i . name + i . nodes . reverse . inject ( '' ) { | nodes_str , j | field = j . render ( j . required or nodes_str != '' or field != '' ) ? field_separator + field + nodes_str : nodes_str } + segment_separator end } end


Input:
render Returns a regexp that matches this particular segment [CODESPLIT] def regexp unless @regexp if self . nodes . find { | i | i . type =~ / / } # It's a very special regexp if there are constant fields
 re_str = self . nodes . inject ( "^#{name}#{Regexp.escape(field_separator)}" ) { | s , i | field_re = i . simple_regexp ( field_separator , segment_separator ) + Regexp . escape ( field_separator ) + '?' field_re = "(#{field_re})?" unless i . required s + field_re } + Regexp . escape ( segment_separator ) @regexp = Regexp . new ( re_str ) else # Simple match
 @regexp = Regexp . new ( "^#{name}#{Regexp.escape(field_separator)}[^#{Regexp.escape(segment_separator)}]*#{Regexp.escape(segment_separator)}" ) end #puts sprintf("%s %p", name, @regexp)
 end @regexp end


Input:
Finds a field in the segment . Returns EMPTY if not found . [CODESPLIT] def find_field ( str ) #puts "Finding field [#{str}] in #{self.class} #{name}"
 # If there is such a field to begin with
 field_num = nil self . nodes . each_index { | i | field_num = i if str == self . nodes [ i ] . name } return EMPTY if field_num . nil? #puts field_num
 # Parse the segment if not parsed already
 unless @fields @fields = self . to_s . chop . split ( Regexp . new ( Regexp . escape ( field_separator ) ) ) self . nodes . each_index { | i | self . nodes [ i ] . content = @fields [ i + 1 ] } end #puts self.nodes[field_num].inspect
 return self . nodes [ field_num ] end


Input:
Creates a parser out of a definition initialize Parse a loop of a given name out of a string . Throws an exception if the loop name is not defined . [CODESPLIT] def parse ( loop_name , str ) loop = @x12_definition [ X12 :: Loop ] [ loop_name ] #puts "Loops to parse #{@x12_definition[X12::Loop].keys}"
 throw Exception . new ( "Cannot find a definition for loop #{loop_name}" ) unless loop loop = loop . dup loop . parse ( str ) return loop end


Input: parse Make an empty loop to be filled out with information [CODESPLIT] def factory ( loop_name ) loop = @x12_definition [ X12 :: Loop ] [ loop_name ] throw Exception . new ( "Cannot find a definition for loop #{loop_name}" ) unless loop loop = loop . dup return loop end


Input: Recursively scan the loop and instantiate fields definitions for all its segments [CODESPLIT] def process_loop ( loop ) loop . nodes . each { | i | case i when X12 :: Loop then process_loop ( i ) when X12 :: Segment then process_segment ( i ) unless i . nodes . size > 0 else return end } end


Input:
Instantiate segment s fields as previously defined [CODESPLIT] def process_segment ( segment ) #puts "Trying to process segment #{segment.inspect}"
 unless @x12_definition [ X12 :: Segment ] && @x12_definition [ X12 :: Segment ] [ segment . name ] # Try to find it in a separate file if missing from the @x12_definition structure
 initialize ( segment . name + '.xml' ) segment_definition = @x12_definition [ X12 :: Segment ] [ segment . name ] throw Exception . new ( "Cannot find a definition for segment #{segment.name}" ) unless segment_definition else segment_definition = @x12_definition [ X12 :: Segment ] [ segment . name ] end segment_definition . nodes . each_index { | i | segment . nodes [ i ] = segment_definition . nodes [ i ] # Make sure we have the validation table if any for this field. Try to read one in if missing.
 table = segment . nodes [ i ] . validation if table unless @x12_definition [ X12 :: Table ] && @x12_definition [ X12 :: Table ] [ table ] initialize ( table + '.xml' ) throw Exception . new ( "Cannot find a definition for table #{table}" ) unless @x12_definition [ X12 :: Table ] && @x12_definition [ X12 :: Table ] [ table ] end end } end


Input:
def regexp [CODESPLIT] def parse ( str ) #puts "Parsing loop #{name}: "+str
 s = str nodes . each { | i | m = i . parse ( s ) s = m if m } if str == s return nil else self . parsed_str = str [ 0 .. - s . length - 1 ] s = do_repeats ( s ) end #puts 'Parsed loop '+self.inspect
 return s end


Input: parse Render all components of this loop as string suitable for EDI [CODESPLIT] def render if self . has_content? self . to_a . inject ( '' ) { | loop_str , i | loop_str += i . nodes . inject ( '' ) { | nodes_str , j | nodes_str += j . render } } else '' end end


Input: Convert a hash ( and it s values recursively ) to NodeBlueprints . This is a helper method allowing a hash to be passed in to Node#properties = when only properties need to be set . One caveat : all node types will default to nt : unstructured . [CODESPLIT] def convert_hash_to_node_blueprint ( hash ) hash . keys . each do | key | if hash [ key ] . is_a? Hash hash [ key ] = convert_hash_to_node_blueprint ( hash [ key ] ) end end NodeBlueprint . new ( :path => :no_path , :properties => hash ) end


Input: format : [ dollars ] [ cents ] only one is required and it must consist only of numbers [CODESPLIT] def validate_response ( value ) if value . select { | k , v | k . in? ( [ 'dollars' , 'cents' ] ) && v . present? } . find { | k , v | ( Float ( v ) rescue nil ) . nil? } . present? "isn't a valid price." end end


Input: for manual use maybe when migrating [CODESPLIT] def calculate_sortable_values response_fieldable . input_fields . each do | response_field | if ( x = response_value ( response_field ) ) . present? get_responses [ "#{response_field.id}_sortable_value" ] = response_field . sortable_value ( x ) end end mark_responses_as_changed! end


Input: Normalizations get run before validation . [CODESPLIT] def normalize_responses return if form . blank? form . response_fields . each do | response_field | if ( x = self . response_value ( response_field ) ) response_field . normalize_response ( x , get_responses ) end end mark_responses_as_changed! end


Input: Audits get run explicitly . [CODESPLIT] def audit_responses form . response_fields . each do | response_field | response_field . audit_response ( self . response_value ( response_field ) , get_responses ) end mark_responses_as_changed! end


Input: Construct a new builder and start building [CODESPLIT] def tag! ( tag , * args , & block ) text , attributes = nil , { } args . each do | arg | case arg when :: Hash attributes . merge! ( arg ) when :: String text ||= '' text << arg end end @stack << [ tag , attributes , text ? [ text ] : [ ] ] if block _process ( block ) end if @stack . length > 1 node = @stack . pop @stack . last [ 2 ] << node NodeBuilder . new ( node , self ) else NodeBuilder . new ( @stack . last , self ) end end


Input: Add Hexp objects to the current tag [CODESPLIT] def << ( * args ) args . each do | arg | if arg . respond_to? ( :to_hexp ) @stack . last [ 2 ] << arg self else :: Kernel . raise :: Hexp :: FormatError , "Inserting literal HTML into a builder with << is deliberately not supported by Hexp" end end end


Input: Replace nodes in a tree [CODESPLIT] def rewrite ( css_selector = nil , & block ) return Rewriter . new ( self , block ) if css_selector . nil? CssSelection . new ( self , css_selector ) . rewrite ( block ) end


Input: Select nodes based on a css selector [CODESPLIT] def select ( css_selector = nil , & block ) if css_selector CssSelection . new ( self , css_selector ) . each ( block ) else Selection . new ( self , block ) end end


Input: Set an attribute used internally by #attr [CODESPLIT] def set_attr ( name , value ) if value . nil? new_attrs = { } attributes . each do | nam , val | new_attrs [ nam ] = val unless nam == name . to_s end else new_attrs = attributes . merge ( name . to_s => value . to_s ) end self . class . new ( self . tag , new_attrs , self . children ) end


Input: * Safely * evaluate a conditional expression [CODESPLIT] def evaluate ( expression , user , resource ) Array ( expression ) . flat_map do | el | if expression? ( el ) cache . fetch ( el ) { type , * ary = el . split ( '::' ) if type == 'user' Array ( ary . inject ( user ) do | rval , attr | rval . freeze . public_send ( attr ) end ) elsif type == 'resource' Array ( ary . inject ( resource ) do | rval , attr | rval . freeze . public_send ( attr ) end ) else raise "Expected #{type} to be 'resource' or 'user'" end } else el end end end


Input: Extend configuration variables [CODESPLIT] def add_configuration ( config_hash ) config_hash . each do | key , val | instance_eval { instance_variable_set ( "@#{key}" , val ) } self . class . instance_eval { attr_accessor key } end end


Input: Check whether pid exists in the current process table . [CODESPLIT] def pid_exists ( pid ) return false if pid < 0 # According to "man 2 kill" PID 0 has a special meaning: # it refers to <<every process in the process group of the # calling process>> so we don't want to go any further. # If we get here it means this UNIX platform *does* have # a process with id 0. return true if pid == 0 :: Process . kill ( 0 , pid ) return true rescue Errno :: ESRCH # No such process return false rescue Errno :: EPERM # EPERM clearly means there's a process to deny access to return true rescue RangeError # the given pid is invalid. return false end


Input: Wait for process with pid pid to terminate and return its exit status code as an integer . [CODESPLIT] def wait_pid ( pid , timeout = nil ) def check_timeout ( delay , stop_at , timeout ) if timeout raise Timeout :: Error . new ( "when waiting for (pid=#{pid})" ) if Time . now >= stop_at end sleep ( delay ) delay * 2 < 0.04 ? delay * 2 : 0.04 end if timeout waitcall = proc { :: Process . wait ( pid , :: Process :: WNOHANG ) } stop_at = Time . now + timeout else waitcall = proc { :: Process . wait ( pid ) } end delay = 0.0001 loop do begin retpid = waitcall . call ( ) rescue Errno :: EINTR delay = check_timeout ( delay , stop_at , timeout ) next rescue Errno :: ECHILD # This has two meanings: # - pid is not a child of Process.pid in which case #   we keep polling until it's gone # - pid never existed in the first place # In both cases we'll eventually return nil as we # can't determine its exit status code. loop do return nil unless pid_exists ( pid ) delay = check_timeout ( delay , stop_at , timeout ) end end unless retpid # WNOHANG was used, pid is still running delay = check_timeout ( delay , stop_at , timeout ) next end # process exited due to a signal; return the integer of # that signal if $? . signaled? return $? . termsig # process exited using exit(2) system call; return the # integer exit(2) system call has been called with elsif $? . exited? return $? . exitstatus else # should never happen raise RuntimeError . new ( "unknown process exit status" ) end end end


Input: upload the content of the module [CODESPLIT] def upload_module_changes ( parent_sha1 , sha1s ) remote_path = fetch_module # search for the first revision that is not  tmp_git_path = clone_or_fetch_repository ( remote_path , module_tmp_git_path ( @remote_path ) ) RIM :: git_session ( tmp_git_path ) do | dest | local_branch = nil remote_branch = nil infos = nil if @module_info . subdir dest_path = File . join ( [ tmp_git_path ] + @module_info . subdir . split ( "/" ) ) else dest_path = tmp_git_path end RIM :: git_session ( @ws_root ) do | src | infos = get_branches_and_revision_infos ( src , dest , parent_sha1 , sha1s ) if infos . branches . size == 1 remote_branch = infos . branches [ 0 ] if dest . has_remote_branch? ( remote_branch ) infos . rev_infos . each do | rev_info | local_branch = create_update_branch ( dest , infos . parent_sha1 , rev_info . src_sha1 ) if ! local_branch copy_revision_files ( src , rev_info . src_sha1 , dest_path , rev_info . rim_info . ignores ) commit_changes ( dest , local_branch , rev_info . src_sha1 , rev_info . message ) end else raise RimException . new ( "The target revision '#{@module_info.target_revision}' of module #{@module_info.local_path} is not a branch. No push can be performed." ) end elsif infos . branches . size > 1 raise RimException . new ( "There are commits for module #{@module_info.local_path} on multiple target revisions (#{infos.branches.join(", ")})." ) end end # Finally we're done. Push the changes if local_branch && dest . rev_sha1 ( local_branch ) != infos . parent_sha1 push_branch = @review && @module_info . remote_branch_format && ! @module_info . remote_branch_format . empty? ? @module_info . remote_branch_format % remote_branch : remote_branch dest . execute ( "git push #{@remote_url} #{local_branch}:#{push_branch}" ) dest . execute ( "git checkout --detach #{local_branch}" ) dest . execute ( "git branch -D #{local_branch}" ) @logger . info ( "Commited changes for module #{@module_info.local_path} to remote branch #{push_branch}." ) else @logger . info ( "No changes to module #{@module_info.local_path}." ) end end end


Input: search backwards for all revision infos [CODESPLIT] def get_branches_and_revision_infos ( src_session , dest_session , parent_sha1 , sha1s ) infos = [ ] branches = [ ] dest_parent_sha1 = nil ( sha1s . size ( ) - 1 ) . step ( 0 , - 1 ) do | i | info = get_revision_info ( src_session , dest_session , sha1s [ i ] ) if ! info . dest_sha1 && info . rim_info . target_revision infos . unshift ( info ) branches . push ( info . rim_info . target_revision ) if ! branches . include? ( info . rim_info . target_revision ) else dest_parent_sha1 = info . dest_sha1 break end end dest_parent_sha1 = get_riminfo_for_revision ( src_session , parent_sha1 ) . revision_sha1 if ! dest_parent_sha1 dest_parent_sha1 = infos . first . rim_info . revision_sha1 if ! dest_parent_sha1 && ! infos . empty? return Struct . new ( :branches , :parent_sha1 , :rev_infos ) . new ( branches , dest_parent_sha1 , infos ) end


Input: collect infos for a revision [CODESPLIT] def get_revision_info ( src_session , dest_session , src_sha1 ) module_status = StatusBuilder . new . rev_module_status ( src_session , src_sha1 , @module_info . local_path ) rim_info = get_riminfo_for_revision ( src_session , src_sha1 ) dest_sha1 = dest_session . rev_sha1 ( "rim-#{src_sha1}" ) msg = src_session . execute ( "git show -s --format=%B #{src_sha1}" ) RevisionInfo . new ( module_status && module_status . dirty? ? dest_sha1 : rim_info . revision_sha1 , src_sha1 , rim_info , msg ) end


Input: commit changes to session [CODESPLIT] def commit_changes ( session , branch , sha1 , msg ) if session . status . lines . any? # add before commit because the path can be below a not yet added path session . execute ( "git add --all" ) msg_file = Tempfile . new ( 'message' ) begin msg_file << msg msg_file . close session . execute ( "git commit -F #{msg_file.path}" ) ensure msg_file . close ( true ) end # create tag session . execute ( "git tag rim-#{sha1} refs/heads/#{branch}" ) end end


Input: get target revision for this module for workspace revision [CODESPLIT] def get_riminfo_for_revision ( session , sha1 ) session . execute ( "git show #{sha1}:#{File.join(@module_info.local_path, RimInfo::InfoFileName)}" ) do | out , e | return RimInfo . from_s ( ! e ? out : "" ) end end


Input: copy files from given source revision into destination dir [CODESPLIT] def copy_revision_files ( src_session , src_sha1 , dest_dir , ignores ) Dir . mktmpdir do | tmp_dir | tmp_dir = Dir . glob ( tmp_dir ) [ 0 ] src_session . execute ( "git archive --format tar #{src_sha1} #{@module_info.local_path} | tar -C #{tmp_dir} -xf -" ) tmp_module_dir = File . join ( tmp_dir , @module_info . local_path ) files = FileHelper . find_matching_files ( tmp_module_dir , false , "/**/*" , File :: FNM_DOTMATCH ) files . delete ( "." ) files . delete ( ".." ) files . delete ( RimInfo :: InfoFileName ) files -= FileHelper . find_matching_files ( tmp_module_dir , false , ignores ) # have source files now. Now clear destination folder and copy prepare_empty_folder ( dest_dir , ".git/**/*" ) files . each do | f | src_path = File . join ( tmp_module_dir , f ) if File . file? ( src_path ) path = File . join ( dest_dir , f ) FileUtils . mkdir_p ( File . dirname ( path ) ) FileUtils . cp ( src_path , path ) end end end end


Input:
status object tree for revision rev returns the root status object which points to any parent status objects note that merge commits mean that the status tree branches at the point were the merged branch branched off the status tree joins i . e . the parent status objects are the same at this point [CODESPLIT] def rev_history_status ( git_session , rev , options = { } ) stop_rev = options [ :stop_rev ] relevant_revs = { } if stop_rev git_session . execute ( "git rev-list #{rev} \"^#{stop_rev}\"" ) . split ( "\n" ) . each do | r | relevant_revs [ r ] = true end elsif options [ :gerrit ] # in gerrit mode, stop on all known commits
 git_session . execute ( "git rev-list #{rev} --not --all --" ) . split ( "\n" ) . each do | r | relevant_revs [ r ] = true end else # remote revs are where we stop traversal
 git_session . all_reachable_non_remote_revs ( rev ) . each do | r | relevant_revs [ r ] = true end end # make sure we deal only with sha1s
 rev = git_session . rev_sha1 ( rev ) build_rev_history_status ( git_session , rev , relevant_revs , { } , :fast => options [ :fast ] ) end


Input:
status object for single revision + rev + without status of ancestors [CODESPLIT] def rev_status ( git_session , rev ) mod_dirs = module_dirs ( git_session , rev ) mod_stats = [ ] # export all relevant modules at once
 # this makes status calculation significantly faster compared
 # to exporting each module separately
 # (e.g. 1.0s instead of 1.5s on linux for a commit with 20 modules)
 git_session . within_exported_rev ( rev , mod_dirs ) do | d | mod_dirs . each do | rel_path | mod_stats << build_module_status ( d , d + "/" + rel_path ) end end stat = RevStatus . new ( mod_stats ) stat . git_rev = git_session . rev_sha1 ( rev ) stat end


Input: status object for a single module at + local_path + in revision + rev + returns nil if there is no such module in this revision [CODESPLIT] def rev_module_status ( git_session , rev , local_path ) mod_stat = nil if git_session . execute ( "git ls-tree -r --name-only #{rev}" ) . split ( "\n" ) . include? ( File . join ( local_path , ".riminfo" ) ) git_session . within_exported_rev ( rev , [ local_path ] ) do | d | mod_stat = build_module_status ( d , File . join ( d , local_path ) ) end end mod_stat end


Input: status object for the current file system content of dir this can by any directory even outside of any git working copy [CODESPLIT] def fs_status ( dir ) RevStatus . new ( fs_rim_dirs ( dir ) . collect { | d | build_module_status ( dir , d ) } ) end


Input:
building of the status of an ancestor chain works by checking the dirty state of modules only when any files affecting some module were changed ; otherwise the status of the module in the ancestor is assumed [CODESPLIT] def build_rev_history_status ( gs , rev , relevant_revs , status_cache = { } , options = { } ) return status_cache [ rev ] if status_cache [ rev ] stat = nil if relevant_revs [ rev ] parent_revs = gs . parent_revs ( rev ) if parent_revs . size > 0 # build status for all parent nodes
 parent_stats = parent_revs . collect do | p | build_rev_history_status ( gs , p , relevant_revs , status_cache , options ) end # if this is a merge commit with multiple parents
 # we decide to use the first commit (git primary parent)
 # note that it's not really important, which one we choose
 # just make sure to use the same commit when checking for changed files
 base_stat = parent_stats . first changed_files = gs . changed_files ( rev , parent_revs . first ) # build list of modules in this commit
 module_dirs = base_stat . modules . collect { | m | m . dir } changed_files . each do | f | if File . basename ( f . path ) == RimInfo :: InfoFileName if f . kind == :added module_dirs << File . dirname ( f . path ) elsif f . kind == :deleted module_dirs . delete ( File . dirname ( f . path ) ) end end end # a module needs to be checked if any of the files within were touched
 check_dirs = module_dirs . select { | d | changed_files . any? { | f | f . path . start_with? ( d ) } } module_stats = [ ] # check out all modules to be checked at once
 if check_dirs . size > 0 gs . within_exported_rev ( rev , check_dirs ) do | ws | check_dirs . each do | d | module_stats << build_module_status ( ws , File . join ( ws , d ) ) end end end ( module_dirs - check_dirs ) . each do | d | base_mod = base_stat . modules . find { | m | m . dir == d } module_stats << RevStatus :: ModuleStatus . new ( d , base_mod . rim_info , base_mod . dirty? ) end stat = RevStatus . new ( module_stats ) stat . git_rev = gs . rev_sha1 ( rev ) stat . parents . concat ( parent_stats ) else # no parents, need to do a full check
 if options [ :fast ] stat = rev_status_fast ( gs , rev ) else stat = rev_status ( gs , rev ) end end else # first "non-relevant", do the full check
 if options [ :fast ] stat = rev_status_fast ( gs , rev ) else stat = rev_status ( gs , rev ) end end status_cache [ rev ] = stat end


Input:
creates a RevStatus object for + rev + with all modules assumend to be clean [CODESPLIT] def rev_status_fast ( git_session , rev ) mod_dirs = module_dirs ( git_session , rev ) mod_stats = [ ] git_session . within_exported_rev ( rev , mod_dirs . collect { | d | "#{d}/#{RimInfo::InfoFileName}" } ) do | temp_dir | mod_dirs . each do | rel_path | mod_stats << RevStatus :: ModuleStatus . new ( rel_path , RimInfo . from_dir ( "#{temp_dir}/#{rel_path}" ) , # never dirty
 false ) end end stat = RevStatus . new ( mod_stats ) stat . git_rev = git_session . rev_sha1 ( rev ) stat end


Input: export + revision + of + mod + into working copy BEWARE : any changes to the working copy target dir will be lost! [CODESPLIT] def export_module ( message ) changes = false RIM :: git_session ( @dest_root ) do | d | start_sha1 = d . rev_sha1 ( "HEAD" ) git_path = module_git_path ( @remote_path ) RIM :: git_session ( git_path ) do | s | if ! s . rev_sha1 ( @module_info . target_revision ) raise RimException . new ( "Unknown target revision '#{@module_info.target_revision}' for module '#{@module_info.local_path}'." ) end local_path = File . join ( @dest_root , @module_info . local_path ) prepare_empty_folder ( local_path , @module_info . ignores ) temp_commit ( d , "clear directory" ) if d . uncommited_changes? strip = "" if @module_info . subdir depth = Pathname ( @module_info . subdir ) . each_filename . count ( ) strip = "--strip-components=#{depth}" end s . execute ( "git archive --format tar #{@module_info.target_revision} #{@module_info.subdir} | tar #{strip} -C #{local_path} -xf -" ) sha1 = s . execute ( "git rev-parse #{@module_info.target_revision}" ) . strip @rim_info = RimInfo . new @rim_info . remote_url = @module_info . remote_url @rim_info . target_revision = @module_info . target_revision @rim_info . revision_sha1 = sha1 @rim_info . ignores = @module_info . ignores . join ( "," ) @rim_info . subdir = @module_info . subdir @rim_info . infos = s . rev_infos ( @module_info . target_revision , RimInfo . git_infos ) @rim_info . to_dir ( local_path ) DirtyCheck . mark_clean ( local_path ) end temp_commit ( d , "commit changes" ) if needs_commit? ( d ) d . execute ( "git reset --soft #{start_sha1}" ) changes = d . uncommited_changes? commit ( d , message || "rim sync: module #{@module_info.local_path}" ) if changes end changes end


Input: sync all module changes into rim branch [CODESPLIT] def sync ( message = nil , rebase = nil , split = true ) # get the name of the current workspace branch RIM :: git_session ( @ws_root ) do | s | branch = s . current_branch || '' rim_branch = "rim/" + branch branch_sha1 = nil changed_modules = nil if branch . empty? raise RimException . new ( "Not on a git branch." ) elsif branch . start_with? ( "rim/" ) raise RimException . new ( "The current git branch '#{branch}' is a rim integration branch. Please switch to a non rim branch to proceed." ) else branch = "refs/heads/#{branch}" branch_sha1 = s . rev_sha1 ( rim_branch ) remote_rev = get_latest_remote_revision ( s , branch ) rev = get_latest_clean_path_revision ( s , branch , remote_rev ) if ! s . has_branch? ( rim_branch ) || has_ancestor? ( s , branch , s . rev_sha1 ( rim_branch ) ) || ! has_ancestor? ( s , rim_branch , remote_rev ) s . execute ( "git branch -f #{rim_branch} #{rev}" ) branch_sha1 = s . rev_sha1 ( rim_branch ) end remote_url = "file://" + @ws_root @logger . debug ( "Folder for temporary git repositories: #{@rim_path}" ) tmpdir = clone_or_fetch_repository ( remote_url , module_tmp_git_path ( ".ws" ) , "Cloning workspace git..." ) RIM :: git_session ( tmpdir ) do | tmp_session | tmp_session . execute ( "git reset --hard" ) tmp_session . execute ( "git clean -xdf" ) # use -f here to prevent git checkout from checking for untracked files which might be overwritten.  # this is safe since we removed any untracked files before. # this is a workaround for a name case problem on windows: # if a file's name changes case between the current head and the checkout target, # git checkout will report the file with the new name as untracked and will fail tmp_session . execute ( "git checkout -B #{rim_branch} -f remotes/origin/#{rim_branch}" ) changed_modules = sync_modules ( tmp_session , message ) if ! split tmp_session . execute ( "git reset --soft #{branch_sha1}" ) commit ( tmp_session , message ? message : get_commit_message ( changed_modules ) ) if tmp_session . uncommited_changes? end tmp_session . execute ( "git push #{remote_url} #{rim_branch}:#{rim_branch}" ) end end if ! changed_modules . empty? if rebase s . execute ( "git rebase #{rim_branch}" ) @logger . info ( "Changes have been commited to branch #{rim_branch} and workspace has been rebased successfully." ) else @logger . info ( "Changes have been commited to branch #{rim_branch}. Rebase to apply changes to workspace." ) end else @logger . info ( "No changes." ) end end end


Input: sync all modules [CODESPLIT] def sync_modules ( session , message ) module_helpers = [ ] @module_infos . each do | module_info | module_helpers . push ( SyncModuleHelper . new ( session . execute_dir , @ws_root , module_info , @logger ) ) end changed_modules = [ ] module_helpers . each do | m | @logger . info ( "Synchronizing #{m.module_info.local_path}..." ) if m . sync ( message ) changed_modules << m . module_info end end changed_modules end


Input: check whether revision has a given ancestor [CODESPLIT] def has_ancestor? ( session , rev , ancestor ) # make sure we deal only with sha1s rev = session . rev_sha1 ( rev ) return rev == ancestor || session . is_ancestor? ( ancestor , rev ) end


Input: get first parent node [CODESPLIT] def get_parent ( session , rev ) parents = session . parent_revs ( rev ) ! parents . empty? ? parents . first : nil end


Input: create default commit message from array of changed modules [CODESPLIT] def get_commit_message ( changed_modules ) StringIO . open do | s | s . puts "rim sync." s . puts changed_modules . each do | m | s . puts m . local_path end s . string end end


Input: ============================================================ | FIELD | DESCRIPTION | AKA | TOP | ============================================================ | rss | resident set size | | RES | | vms | total program size | size | VIRT | | shared | shared pages ( from shared mappings ) | | SHR | | text | text ( code ) | trs | CODE | | lib | library ( unused in Linux 2 . 6 ) | lrs | | | data | data + stack | drs | DATA | | dirty | dirty pages ( unused in Linux 2 . 6 ) | dt | | ============================================================ [CODESPLIT] def memory_info_ex info = File . new ( "/proc/#{@pid}/statm" ) . readline . split [ 0 ... 7 ] vms , rss , shared , text , lib , data , dirty = info . map { | i | i . to_i * PAGE_SIZE } OpenStruct . new ( vms : vms , rss : rss , shared : shared , text : text , lib : lib , data : data , dirty : dirty ) end


Input: data in pmmap_ext is an Array [CODESPLIT] def pmmap_ext ( data ) pmmap_ext = [ 'addr' , 'perms' , 'path' , 'rss' , 'size' , 'pss' , 'shared_clean' , 'shared_dirty' , 'private_clean' , 'private_dirty' , 'referenced' , 'anonymous' , 'swap' ] os_list = [ ] data . each do | datum | os = OpenStruct . new pmmap_ext . each_index { | i | os [ pmmap_ext [ i ] ] = datum [ i ] } os_list . push ( os ) end os_list end


Input: data in pmmap_grouped is a Hash [CODESPLIT] def pmmap_grouped ( data ) pmmap_grouped = [ 'rss' , 'size' , 'pss' , 'shared_clean' , 'shared_dirty' , 'private_clean' , 'private_dirty' , 'referenced' , 'anonymous' , 'swap' ] os_list = [ ] data . each do | k , v | os = OpenStruct . new os . path = k pmmap_grouped . each_index { | i | os [ pmmap_grouped [ i ] ] = v [ i ] } os_list . push ( os ) end os_list end


Input:
returns nil if checksum can t be calculated due to missing info [CODESPLIT] def calc_checksum ( mi , dir ) if check_required_attributes ( mi ) sha1 = Digest :: SHA1 . new # all files and directories within dir
 files = FileHelper . find_matching_files ( dir , false , "/**/*" , File :: FNM_DOTMATCH ) # Dir.glob with FNM_DOTMATCH might return . and ..
 files . delete ( "." ) files . delete ( ".." ) # ignore the info file itself
 files . delete ( RimInfo :: InfoFileName ) # ignores defined by user
 files -= FileHelper . find_matching_files ( dir , false , mi . ignores ) # order of files makes a difference
 # sort to eliminate platform specific glob behavior
 files . sort! files . each do | fn | update_file ( sha1 , dir , fn ) end ChecksumAttributes . each do | a | sha1 . update ( mi . send ( a ) ) end sha1 . hexdigest else # can't calc checksum
 nil end end


Input: returns the current branch [CODESPLIT] def current_branch out = execute "git branch" out . split ( "\n" ) . each do | l | if ! l . include? ( '(' ) && ( l =~ / \* \s \S / ) return $1 end end nil end


Input: check whether remote branch exists [CODESPLIT] def has_remote_branch? ( branch ) out = execute ( "git ls-remote --heads" ) out . split ( "\n" ) . each do | l | return true if l . split ( / \s / ) [ 1 ] == "refs/heads/#{branch}" end false end


Input: returns the SHA - 1 representation of rev [CODESPLIT] def rev_sha1 ( rev ) sha1 = nil execute "git rev-list -n 1 #{rev} --" do | out , e | sha1 = out . strip if ! e end sha1 end


Input: returns some informations about a revision [CODESPLIT] def rev_infos ( rev , desired ) info = { } desired . each_pair do | key , value | execute "git log -1 --format=#{value} #{rev} --" do | out , e | info [ key ] = out . strip if ! e end end info end


Input: returns the SHA - 1 representations of the heads of all remote branches [CODESPLIT] def remote_branch_revs out = execute "git show-ref" out . split ( "\n" ) . collect { | l | if l =~ / \/ \/ / l . split [ 0 ] else nil end } . compact end


Input:
export file contents of rev to dir if + paths + is given and non - empty checks out only those parts of the filesystem tree does not remove any files from dir which existed before [CODESPLIT] def export_rev ( rev , dir , paths = [ ] ) paths = paths . dup loop do path_args = "" # max command line length on Windows XP and higher is 8191
 # consider the following extra characters which will be added:
 # up to 3 paths in execute, 1 path for tar, max path length 260 = 1040
 # plus some "glue" characters, plus the last path item with 260 max;
 # use 6000 to be on the safe side
 while ! paths . empty? && path_args . size < 6000 path_args << " " path_args << paths . shift end execute "git archive --format tar #{rev} #{path_args} | tar -C #{dir} -xf -" break if paths . empty? end end


Input:
checks out rev to a temporary directory and yields this directory to the given block if + paths + is given and non - empty checks out only those parts of the filesystem tree returns the value returned by the block [CODESPLIT] def within_exported_rev ( rev , paths = [ ] ) Dir . mktmpdir ( "rim" ) do | d | d = Dir . glob ( d ) [ 0 ] c = File . join ( d , "content" ) FileUtils . mkdir ( c ) export_rev ( rev , c , paths ) # return contents of yielded block
 # mktmpdir returns value return by our block
 yield c FileUtils . rm_rf ( c ) # retry to delete if it hasn't been deleted yet
 # this could be due to Windows keeping the files locked for some time
 # this is especially a problem if the machine is at its limits
 retries = 600 while File . exist? ( c ) && retries > 0 sleep ( 0.1 ) FileUtils . rm_rf ( c ) retries -= 1 end if File . exist? ( c ) @logger . warn "could not delete temp dir: #{c}" end end end


Input: returns a list of all files which changed in commit + rev + together with the kind of the change ( : modified : deleted : added ) [CODESPLIT] def changed_files ( rev , rev_from = nil ) out = execute "git diff-tree -r --no-commit-id #{rev_from} #{rev}" out . split ( "\n" ) . collect do | l | cols = l . split path = cols [ 5 ] kind = case cols [ 4 ] when "M" :modified when "A" :added when "D" :deleted else nil end ChangedFile . new ( path , kind ) end end


Input: upload all module changes into corresponding remote repositories [CODESPLIT] def upload # get the name of the current workspace branch RIM :: git_session ( @ws_root ) do | s | branch = s . current_branch if branch . nil? raise RimException . new ( "Not on a git branch." ) elsif ! branch . start_with? ( "rim/" ) begin sha1 = s . rev_sha1 ( branch ) @logger . info ( "Uploading modules..." ) upload_modules ( get_upload_revisions ( s , sha1 ) ) ensure s . execute ( "git checkout -B #{branch}" ) end else raise RimException . new ( "The current git branch '#{branch}' is a rim integration branch. Please switch to a non rim branch to proceed." ) end end end


Input: upload all modules [CODESPLIT] def upload_modules ( info ) each_module_parallel ( "uploading" , @module_helpers ) do | m | m . upload ( info . parent , info . sha1s ) end end


Input: get revisions to upload i . e . the revisions up to the last remote revision the function returns the revisions in order of appearal i . e . the oldest first [CODESPLIT] def get_upload_revisions ( session , rev ) # remote revs are where we stop traversal non_remote_revs = { } session . all_reachable_non_remote_revs ( rev ) . each do | r | non_remote_revs [ r ] = true end revisions = [ ] # make sure we deal only with sha1s rev = session . rev_sha1 ( rev ) while rev && non_remote_revs [ rev ] revisions . push ( rev ) parents = session . parent_revs ( rev ) rev = parents . size > 0 ? parents . first : nil end Struct . new ( :parent , :sha1s ) . new ( rev , revisions . reverse! ) end


Input: fetch module + mod + into the . rim folder works both for initial fetch and updates [CODESPLIT] def fetch_module FileUtils . mkdir_p git_path RIM :: git_session ( git_path ) do | s | if ! File . exist? ( git_path + "/config" ) s . execute ( "git clone --mirror #{@remote_url} #{git_path}" ) do | out , e | raise RimException . new ( "Remote repository '#{@remote_url}' of module '#{@module_info.local_path}' not found." ) if e end else s . execute ( "git remote update" ) end end git_path end


Input: prepare empty folder : remove all files not on the ignore list and empty folders [CODESPLIT] def prepare_empty_folder ( local_path , ignores ) ignores = FileHelper . find_matching_files ( local_path , true , ignores ) FileHelper . find_matching_files ( local_path , true , "/**/*" , File :: FNM_DOTMATCH ) . each do | f | if File . file? ( f ) && ! ignores . include? ( f ) FileUtils . rm ( f ) end end FileHelper . remove_empty_dirs ( local_path ) FileUtils . mkdir_p ( local_path ) end


Input: def determine_role ( args ) args [ : atc ] == false ? role = pilot : role = all args [ : pilots ] == false ? role = atc : role = role role = all if args [ : pilots ] == false && args [ : atc ] == false role end [CODESPLIT] def stations stations = [ ] CSV . foreach ( LOCAL_DATA , :col_sep => ':' ) do | row | callsign , origin , destination , client = row [ 0 ] . to_s , row [ 11 ] . to_s , row [ 13 ] . to_s , row [ 3 ] . to_s for cs in @callsign stations << row if callsign [ 0 ... cs . length ] == cs # && client == "ATC") unless @role == "pilot" # stations << row if (origin[0...icao.length] == icao || destination[0...icao.length] == icao) unless @role == "atc" end end stations end


Input: Assign the value to the given attribute of the item [CODESPLIT] def assign ( attribute , value ) unless value == :skip || attribute == :class if item . respond_to? ( "#{attribute}=" ) item . send ( "#{attribute}=" , value ) elsif item . is_a? ( Hash ) item [ attribute ] = value end end end


Input: Nicked from here : http : // gist . github . com / 301173 [CODESPLIT] def get_constant ( name_sym ) return name_sym if name_sym . is_a? Class name = name_sym . to_s . split ( '_' ) . collect { | s | s . capitalize } . join ( '' ) Object . const_defined? ( name ) ? Object . const_get ( name ) : Object . const_missing ( name ) end


Input: Can be left in your tests as an alternative to build and to warn if your factory method ever starts producing invalid instances [CODESPLIT] def debug ( * args ) item = build ( args ) invalid_item = Array ( item ) . find ( :invalid? ) if invalid_item if invalid_item . errors . respond_to? ( :messages ) errors = invalid_item . errors . messages else errors = invalid_item . errors end raise "Oops, the #{invalid_item.class} created by the Factory has the following errors: #{errors}" end item end


Input: Look for errors in factories and ( optionally ) their traits . Parameters : factory_names - which factories to lint ; omit for all factories options : traits : true - to lint traits as well as factories [CODESPLIT] def lint! ( factory_names : nil , traits : false ) factories_to_lint = Array ( factory_names || self . factory_names ) strategy = traits ? :factory_and_traits : :factory Linter . new ( self , factories_to_lint , strategy ) . lint! end


Input: Execute the requested factory method crank out the target object! [CODESPLIT] def crank_it ( what , overrides ) if what . to_s =~ / / what = $1 overrides = overrides . merge ( :_return_attributes => true ) end item = "TBD" new_job ( what , overrides ) do item = self . send ( what ) # Invoke the factory method item = apply_traits ( what , item ) end item end


Input: Send missing methods to view_context first [CODESPLIT] def method_missing ( method , * args , & block ) if view_context . respond_to? ( method , true ) view_context . send ( method , args , block ) else super end end


Input: Wrap an object or collection of objects with a presenter class . [CODESPLIT] def present ( object , presenter : nil , ** args ) if object . respond_to? ( :to_ary ) object . map { | item | present ( item , presenter : presenter , ** args ) } else presenter ||= presenter_klass ( object ) wrapper = presenter . new ( object , view_context , ** args ) block_given? ? yield ( wrapper ) : wrapper end end


Input: Build booking [CODESPLIT] def build_booking ( params = { } , template_code = nil ) template_code ||= self . class . to_s . underscore + ':invoice' booking_template = BookingTemplate . find_by_code ( template_code ) # Prepare booking parameters booking_params = { reference : self } booking_params . merge! ( params ) # Build and assign booking booking = booking_template . build_booking ( booking_params ) bookings << booking booking end


Input: Supported options : : tag_prefix - use a custom prefix for Git tags ( defaults to v ) Publish the gem if its version has changed since the last release . [CODESPLIT] def publish_if_updated ( method , options = { } ) return if version_released? @builder . build ( @gemspec ) . tap { | gem | @pusher . push gem , method , options @git_remote . add_tag "#{@tag_prefix}#{@version}" } end


Input: Publish the gem . [CODESPLIT] def push ( gem , method , options = { } ) push_command = PUSH_METHODS [ method . to_s ] or raise "Unknown Gem push method #{method.inspect}." push_command += [ gem ] push_command += [ "--as" , options [ :as ] ] if options [ :as ] @cli_facade . execute ( push_command ) end


Input: Disc s #enqueue is the main user - facing method of a Disc job it enqueues a job with a given set of arguments in Disque so it can be picked up by a Disc worker process . [CODESPLIT] def enqueue ( args = [ ] , at : nil , queue : nil , ** options ) options = disc_options . merge ( options ) . tap do | opt | opt [ :delay ] = at . to_time . to_i - DateTime . now . to_time . to_i unless at . nil? end disque . push ( queue || self . queue , Disc . serialize ( { class : self . name , arguments : Array ( args ) } ) , Disc . disque_timeout , options ) end


Input: Constructor for all One Dimensional interpolation operations . [CODESPLIT] def interpolate interpolant case @opts [ :type ] when :linear for_each ( interpolant ) { | x | linear_interpolation ( x ) } when :cubic cubic_spline_interpolation interpolant else raise ArgumentError , "1 D interpolation of type #{@opts[:type]} not supported" end end


Input: Linear interpolation functions [CODESPLIT] def for_each interpolant result = [ ] if interpolant . kind_of? Numeric return yield interpolant else interpolant . each { | x | result << yield ( x ) } end result end


Input: References : Numerical Recipes Edition 3 . Chapter 3 . 3 [CODESPLIT] def compute_second_derivatives_for y y_sd = Array . new ( @size ) n = y_sd . size u = Array . new ( n - 1 ) yp1 = @opts [ :yp1 ] # first derivative of the 0th point as specified by the user ypn = @opts [ :ypn ] # first derivative of the nth point as specified by the user qn , un = nil , nil if yp1 > 0.99E30 y_sd [ 0 ] , u [ 0 ] = 0.0 , 0.0 else y_sd [ 0 ] = - 0.5 u [ 0 ] = ( 3.0 / ( @x [ 1 ] - @x [ 0 ] ) ) * ( ( y [ 1 ] - y [ 0 ] ) / ( @x [ 1 ] - @x [ 0 ] ) - yp1 ) end 1 . upto ( n - 2 ) do | i | # decomposition loop for tridiagonal algorithm sig = ( @x [ i ] - @x [ i - 1 ] ) / ( @x [ i + 1 ] - @x [ i - 1 ] ) p = sig * y_sd [ i - 1 ] + 2 y_sd [ i ] = ( sig - 1 ) / p u [ i ] = ( ( y [ i + 1 ] - y [ i ] ) / ( @x [ i + 1 ] - @x [ i ] ) ) - ( ( y [ i ] - y [ i - 1 ] ) / ( @x [ i ] - @x [ i - 1 ] ) ) u [ i ] = ( 6 * u [ i ] / ( @x [ i + 1 ] - @x [ i - 1 ] ) - sig * u [ i - 1 ] ) / p ; end if ypn > 0.99E30 qn , un = 0.0 , 0.0 else qn = 0.5 un = ( 3.0 / ( @x [ n - 1 ] - @x [ n - 2 ] ) ) * ( ypn - ( y [ n - 1 ] - y [ n - 2 ] ) / ( @x [ n - 1 ] - @x [ n - 2 ] ) ) end y_sd [ n - 1 ] = ( un - qn * u [ n - 2 ] ) / ( qn * y_sd [ n - 2 ] + 1.0 ) ( n - 2 ) . downto ( 0 ) do | k | y_sd [ k ] = y_sd [ k ] * y_sd [ k + 1 ] + u [ k ] end y_sd end


Input: Reads the specified file as individual lines filters them using the * selector * ( if provided ) and returns those lines in an array . [CODESPLIT] def read_lines ( filename , selector ) if selector IO . foreach ( filename ) . select . with_index ( 1 , selector ) else open ( filename , :read ) end end


Input: Finds and initializes a lines selector that can handle the specified include . [CODESPLIT] def lines_selector_for ( target , attributes ) if ( klass = @selectors . find { | s | s . handles? target , attributes } ) klass . new ( target , attributes , logger : logger ) end end


Input: @param attributes [ Hash<String String > ] the attributes parsed from the include :: [] s attributes slot . It must contain a key lines . Returns true if the given line should be included false otherwise . [CODESPLIT] def include? ( _ , line_num ) return false if @ranges . empty? ranges = @ranges ranges . pop while ! ranges . empty? && ranges . last . last < line_num ranges . last . cover? ( line_num ) if ! ranges . empty? end


Input: @param target [ String ] name of the source file to include as specified in the target slot of the include :: [] directive . @param attributes [ Hash<String String > ] the attributes parsed from the include :: [] s attributes slot . It must contain a key tag or tags . @param logger [ Logger ] Returns true if the given line should be included false otherwise . [CODESPLIT] def include? ( line , line_num ) tag_type , tag_name = parse_tag_directive ( line ) case tag_type when :start enter_region! ( tag_name , line_num ) false when :end exit_region! ( tag_name , line_num ) false when nil if @state && @first_included_lineno . nil? @first_included_lineno = line_num end @state end end


Input: Generates a <body > tag with HTML5 data attributes for the controller & action name . The keyword arguments are forwarded to tag and content_tag . [CODESPLIT] def body_tag ( params_as_metadata : false , ** kwargs ) options = kwargs . deep_merge ( data : data_attrs ( params_as_metadata ) ) if block_given? content_tag ( :body , options ) { yield } else tag ( :body , options , true ) end end


Input: : nodoc : Establishes a connection to the database that s used by all Active Record objects [CODESPLIT] def ovirt_legacy_postgresql_connection ( config ) conn_params = config . symbolize_keys conn_params . delete_if { | _ , v | v . nil? } # Map ActiveRecords param names to PGs. conn_params [ :user ] = conn_params . delete ( :username ) if conn_params [ :username ] conn_params [ :dbname ] = conn_params . delete ( :database ) if conn_params [ :database ] # Forward only valid config params to PGconn.connect. valid_conn_param_keys = PGconn . conndefaults_hash . keys + [ :requiressl ] conn_params . slice! ( valid_conn_param_keys ) # The postgres drivers don't allow the creation of an unconnected PGconn object, # so just pass a nil connection object for the time being. ConnectionAdapters :: OvirtLegacyPostgreSQLAdapter . new ( nil , logger , conn_params , config ) end


Input: Internal methods : Append data as query params to an endpoint [CODESPLIT] def do_request method , action , query = { } url = @neto_url options = { } header_action = { "NETOAPI_ACTION" => action } #set headers options [ :headers ] = @header_args . merge ( header_action ) #set body case action when 'GetItem' if query . empty? options . merge! ( body : { "Filter" => @body_defaults } . to_json ) else body_args = @body_defaults . merge ( query ) options . merge! ( body : { "Filter" => body_args } . to_json ) end when 'AddItem' options . merge! ( body : { "Item" => [ query ] } . to_json ) when 'UpdateItem' options . merge! ( body : { "Item" => [ query ] } . to_json ) end HTTParty . send ( method , url , options ) end


Input: Works just like the standard rand () function . If called with an integer argument rand () will return positive random number in the range of 0 to ( argument - 1 ) . If called without an integer argument rand () returns a positive floating point number less than 1 . If called with a Range returns a number that is in the range . [CODESPLIT] def rand ( arg = nil ) if @randcnt == 1 isaac @randcnt = 256 end @randcnt -= 1 if arg . nil? ( @randrsl [ @randcnt ] / 536_870_912.0 ) % 1 elsif arg . is_a? ( Integer ) @randrsl [ @randcnt ] % arg elsif arg . is_a? ( Range ) arg . min + @randrsl [ @randcnt ] % ( arg . max - arg . min ) else @randrsl [ @randcnt ] % arg . to_i end end


Input: rubocop : disable Style / Semicolon [CODESPLIT] def isaac i = 0 @cc += 1 @bb += @cc @bb &= 0xffffffff while i < 256 x = @mm [ i ] @aa = ( @mm [ ( i + 128 ) & 255 ] + ( @aa ^ ( @aa << 13 ) ) ) & 0xffffffff @mm [ i ] = y = ( @mm [ ( x >> 2 ) & 255 ] + @aa + @bb ) & 0xffffffff @randrsl [ i ] = @bb = ( @mm [ ( y >> 10 ) & 255 ] + x ) & 0xffffffff i += 1 x = @mm [ i ] @aa = ( @mm [ ( i + 128 ) & 255 ] + ( @aa ^ ( 0x03ffffff & ( @aa >> 6 ) ) ) ) & 0xffffffff @mm [ i ] = y = ( @mm [ ( x >> 2 ) & 255 ] + @aa + @bb ) & 0xffffffff @randrsl [ i ] = @bb = ( @mm [ ( y >> 10 ) & 255 ] + x ) & 0xffffffff i += 1 x = @mm [ i ] @aa = ( @mm [ ( i + 128 ) & 255 ] + ( @aa ^ ( @aa << 2 ) ) ) & 0xffffffff @mm [ i ] = y = ( @mm [ ( x >> 2 ) & 255 ] + @aa + @bb ) & 0xffffffff @randrsl [ i ] = @bb = ( @mm [ ( y >> 10 ) & 255 ] + x ) & 0xffffffff i += 1 x = @mm [ i ] @aa = ( @mm [ ( i + 128 ) & 255 ] + ( @aa ^ ( 0x0000ffff & ( @aa >> 16 ) ) ) ) & 0xffffffff @mm [ i ] = y = ( @mm [ ( x >> 2 ) & 255 ] + @aa + @bb ) & 0xffffffff @randrsl [ i ] = @bb = ( @mm [ ( y >> 10 ) & 255 ] + x ) & 0xffffffff i += 1 end end


Input: Create a Core object . [CODESPLIT] def run client_ip = @ip key = "request_count:#{client_ip}" result = { status : Constants :: SUCCESS_STATUS , message : Constants :: OK_MESSAGE } requests_count = @storage . get ( key ) unless requests_count @storage . set ( key , 0 ) @storage . expire ( key , @limits [ "time_period_seconds" ] ) end if requests_count . to_i >= @limits [ "max_requests_count" ] result [ :status ] = Constants :: EXPIRED_STATUS result [ :message ] = message ( period ( key ) ) else @storage . incr ( key ) end result end


Input: Render a set of radio buttons . Takes a method name an array of choices ( just like a + select + field ) and an Informant options hash . [CODESPLIT] def radio_buttons ( method , choices , options = { } ) choices . map! { | i | i . is_a? ( Array ) ? i : [ i ] } build_shell ( method , options , "radio_buttons_field" ) do choices . map { | c | radio_button method , c [ 1 ] , :label => c [ 0 ] , :label_for => [ object_name , method , c [ 1 ] . to_s . downcase ] . join ( '_' ) } end end


Input: Render a set of check boxes for selecting HABTM - associated objects . Takes a method name ( eg category_ids ) an array of choices ( just like a + select + field ) and an Informant options hash . In the default template the check boxes are enclosed in a <div > with CSS class <tt > habtm_check_boxes< / tt > which can be styled thusly to achieve a scrolling list : [CODESPLIT] def habtm_check_boxes ( method , choices , options = { } ) choices . map! { | i | i . is_a? ( Array ) ? i : [ i ] } base_id = "#{object_name}_#{method}" base_name = "#{object_name}[#{method}]" @template . hidden_field_tag ( "#{base_name}[]" , "" , :id => "#{base_id}_empty" ) + build_shell ( method , options , "habtm_check_boxes_field" ) do choices . map do | c | field_id = "#{base_id}_#{c[1].to_s.downcase}" habtm_single_check_box_template ( :name => "#{base_name}[]" , :id => field_id , :value => c [ 1 ] , :checked => @object . send ( method ) . include? ( c [ 1 ] ) , :label => @template . label_tag ( field_id , c [ 0 ] ) ) end end end


Input: Standard Rails date selector . [CODESPLIT] def date_select ( method , options = { } ) options [ :include_blank ] ||= false options [ :start_year ] ||= 1801 options [ :end_year ] ||= Time . now . year options [ :label_for ] = "#{object_name}_#{method}_1i" build_shell ( method , options ) { super } end


Input: This differs from the Rails - default date_select in that it submits three distinct fields for storage in three separate attributes . This allows for partial dates ( eg 1984 or October 1984 ) . See { FlexDate } [ http : // github . com / alexreisner / flex_date ] for storing and manipulating partial dates . [CODESPLIT] def multipart_date_select ( method , options = { } ) options [ :include_blank ] ||= false options [ :start_year ] ||= 1801 options [ :end_year ] ||= Time . now . year options [ :prefix ] = object_name # for date helpers options [ :label_for ] = "#{object_name}_#{method}_y" build_shell ( method , options ) do [ [ 'y' , 'year' ] , [ 'm' , 'month' ] , [ 'd' , 'day' ] ] . map { | p | i , j = p value = @object . send ( method . to_s + '_' + i ) options [ :field_name ] = method . to_s + '_' + i eval ( "@template.select_#{j}(#{value.inspect}, options)" ) } . join ( ' ' ) end end


Input: Year select field . Takes options <tt > : start_year< / tt > and <tt > : end_year< / tt > and <tt > : step< / tt > . [CODESPLIT] def year_select ( method , options = { } ) options [ :first ] = options [ :start_year ] || 1801 options [ :last ] = options [ :end_year ] || Date . today . year integer_select ( method , options ) end


Input: Integer select field . Takes options <tt > : first< / tt > <tt > : last< / tt > and <tt > : step< / tt > . [CODESPLIT] def integer_select ( method , options = { } ) options [ :step ] ||= 1 choices = [ ] ; i = 0 ( options [ :first ] .. options [ :last ] ) . each do | n | choices << n if i % options [ :step ] == 0 i += 1 end select method , choices , options end


Input: Submit button with smart default text ( if + value + is nil uses Create for new record or Update for old record ) . [CODESPLIT] def submit ( value = nil , options = { } ) value = ( @object . new_record? ? "Create" : "Update" ) if value . nil? build_shell ( value , options , 'submit_button' ) { super } end


Input: Render a field label . [CODESPLIT] def label ( method , text = nil , options = { } ) colon = false if options [ :colon ] . nil? options [ :for ] = options [ :label_for ] required = options [ :required ] # remove special options options . delete :colon options . delete :label_for options . delete :required text = @template . send ( :h , text . blank? ? method . to_s . humanize : text . to_s ) text << ':' . html_safe if colon text << @template . content_tag ( :span , "*" , :class => "required" ) if required super end


Input: Render a field set ( HTML <fieldset > ) . Takes the legend ( optional ) an options hash and a block in which fields are rendered . [CODESPLIT] def field_set ( legend = nil , options = nil , & block ) @template . content_tag ( :fieldset , options ) do ( legend . blank? ? "" : @template . content_tag ( :legend , legend ) ) + @template . capture ( block ) end end


Input: --------------------------------------------------------------- [CODESPLIT] def build_shell ( method , options , template = 'default_field' ) #:nodoc: # Build new options hash for custom label options. label_options = options . reject { | i , j | ! @@custom_label_options . include? i } # Build new options hash for custom field options. field_options = options . reject { | i , j | ! @@custom_field_options . include? i } # Remove custom options from options hash so things like # <tt>include_blank</tt> aren't added as HTML attributes. options . reject! { | i , j | @@custom_options . include? i } locals = { :element => yield , :label => label ( method , field_options [ :label ] , label_options ) , :description => field_options [ :description ] , :div_id => "#{@object_name}_#{method}_field" , :required => field_options [ :required ] , :decoration => field_options [ :decoration ] || nil } send ( "#{template}_template" , locals ) . html_safe end


Input:
Render a group of HABTM check boxes . [CODESPLIT] def habtm_check_boxes_field_template ( l = { } ) <<-END #{ l [ :div_id ] } #{ l [ :label ] } #{ l [ :element ] . join } #{ l [ :decoration ] } #{ "
#{l[:description]}
" unless l [ :description ] . blank? } END end


Input: Called when parsing . While you can override this in subclasses in general it is probably better to use the on_unpack method to define a proc to handle unpacking for special cases . [CODESPLIT] def read ( raw , predecessors = nil ) if raw . respond_to? ( :read ) raw = raw . read ( self . sizeof ( ) ) end if raw . size < self . sizeof ( ) raise ( ReadError , "Expected #{self.sizeof} bytes, but only got #{raw.size} bytes" ) end vals = if @unpack_cb @unpack_cb . call ( raw , predecessors ) else raw . unpack ( self . format ) end return ( self . claim_value ( vals , predecessors ) ) end


Input: Called when composing raw data . While you can override this in subclasses in general it is probably better to use the on_pack method to define a proc to handle packing for special cases . [CODESPLIT] def pack_value ( val , obj = nil ) begin if @pack_cb @pack_cb . call ( val , obj ) else varray = val . is_a? ( Array ) ? val : [ val ] varray . pack ( self . format ) end rescue => e raise ( PackError , "Error packing #{val.inspect} as type #{self.name.inspect} -- #{e.class} -> #{e}" ) end end


Input: Take the following C struct for example : [CODESPLIT] def struct ( name , opts = { } , & block ) Rstruct :: Structure . new ( name , opts , block ) end


Input: Image resize [CODESPLIT] def ires_tag ( path , width : nil , height : nil , type : Type :: ALL , mode : Mode :: RESIZE , expire : 30 . days , ** option ) image_path = Ires :: Service . path ( path , width : width || 0 , height : height || 0 , mode : mode , type : type , expire : expire ) # Set image_tag image_tag ( image_path , option ) end


Input: Replacing RSpec s default method_missing implementation so that we can include our own special default hooks that allows spec tests to look more readable . [CODESPLIT] def method_missing ( sym , * args , & block ) # # Note: Be sure that the symbol does not contain the word "test". test # is a private method on Ruby objects and will cause the Be and Has # matches to fail. # return Lebowski :: RSpec :: Matchers :: Be . new ( sym , args ) if sym . to_s =~ / / return Lebowski :: RSpec :: Matchers :: Has . new ( sym , args ) if sym . to_s =~ / / return Lebowski :: RSpec :: Operators :: That . new ( sym , args ) if sym . to_s =~ / / super end


Input: This method searches for folders and files in the assets root directory . After searching all files stores in an array and then copying to the folder _site . [CODESPLIT] def static_files source = File . dirname ( ENGINE . assets_path ) asset_files . map do | file | dir = File . dirname ( file ) file_name = File . basename ( file ) Jekyll :: StaticFile . new @site , source , dir , file_name end end


Input: Get paths and fils directory assets [CODESPLIT] def asset_files asset_files = [ ] Find . find ( ENGINE . assets_path ) . each do | path | next if File . directory? ( path ) next if path . include? ( ENGINE . stylesheets_sass_path ) asset_files << path . sub ( ENGINE . assets_path , 'assets' ) end asset_files end


Input: high level functions [CODESPLIT] def daily ( time = Date . today , page_size = 50 ) time = time . strftime ( "%Y-%m-%d" ) unless time . is_a? ( String ) report_id = run_report_request ( 'DailyActivityReport' , { 'report_date' => time } , page_size ) meta_data = get_meta_data_request ( report_id ) data = [ ] meta_data [ "numberOfPages" ] . to_i . times do | page_num | data += get_data_request ( report_id , page_num + 1 ) #it's zero indexed end data end


Input: low level functions [CODESPLIT] def run_report_request ( report_name , report_params = { } , page_size = 50 ) response = request 'runReportRequest' do | xml | xml . reportName report_name report_params . each do | name , value | xml . reportParam do xml . paramName name xml . paramValue value end end xml . pageSize page_size end response . elements [ "runReportResponse/reportId" ] . get_text . value end


Input: Generate a unique field [CODESPLIT] def generate_unique ( length = 32 , & blk ) unique = generate_random ( length ) unique = generate_random ( length ) until blk . call ( unique ) unique end


Input: High level method to draw the paperback content on the pdf document [CODESPLIT] def draw_paperback ( qr_code : , sixword_lines : , sixword_bytes : , labels : , passphrase_sha : nil , passphrase_len : nil , sixword_font_size : nil , base64_content : nil , base64_bytes : nil ) unless qr_code . is_a? ( RQRCode :: QRCode ) raise ArgumentError . new ( 'qr_code must be RQRCode::QRCode' ) end # Header & QR code page pdf . font ( 'Times-Roman' ) debug_draw_axes draw_header ( labels : labels , passphrase_sha : passphrase_sha , passphrase_len : passphrase_len ) add_newline draw_qr_code ( qr_modules : qr_code . modules ) pdf . stroke_color '000000' pdf . fill_color '000000' # Sixword page pdf . start_new_page draw_sixword ( lines : sixword_lines , sixword_bytes : sixword_bytes , font_size : sixword_font_size , is_encrypted : passphrase_len ) if base64_content draw_base64 ( b64_content : base64_content , b64_bytes : base64_bytes , is_encrypted : passphrase_len ) end pdf . number_pages ( '<page> of <total>' , align : :right , at : [ pdf . bounds . right - 100 , - 2 ] ) end


Input: Generates a glob file pattern for the specified list of locales ( i . e . IETF language tags ) [CODESPLIT] def pattern_from ( locales ) locales = Array ( locales || [ ] ) locales = locales . map { | locale | subpatterns_from locale } . flatten pattern = locales . blank? ? '*' : "{#{locales.join ','}}" "#{base_pattern}#{pattern}#{extension}" end


Input: Generates subpatterns for the specified locale ( i . e . IETF language tag ) . Subpatterns are all more generic variations of a locale . E . g . subpatterns for en - US are en - US and en . Subpatterns for az - Latn - IR are az - Latn - IR az - Latn and az [CODESPLIT] def subpatterns_from ( locale ) parts = locale . to_s . split ( '-' ) parts . map . with_index { | part , index | parts [ 0 .. index ] . join ( '-' ) } end


Input: Produces and processes a report for use in the report method It takes the same arguments as report and returns the same object as process_report [CODESPLIT] def produce_report ( * args ) # Check xcov availability, install it if needed ` ` unless xcov_available? unless xcov_available? puts "xcov is not available on this machine" return end require "xcov" require "fastlane_core" # Init Xcov config = FastlaneCore :: Configuration . create ( Xcov :: Options . available_options , convert_options ( args . first ) ) Xcov . config = config Xcov . ignore_handler = Xcov :: IgnoreHandler . new # Init project manager = Xcov :: Manager . new ( config ) # Parse .xccoverage report_json = manager . parse_xccoverage # Map and process report process_report ( Xcov :: Report . map ( report_json ) ) end


Input: Outputs a processed report with Danger [CODESPLIT] def output_report ( report ) # Create markdown report_markdown = report . markdown_value # Send markdown markdown ( report_markdown ) # Notify failure if minimum coverage hasn't been reached threshold = Xcov . config [ :minimum_coverage_percentage ] . to_i if ! threshold . nil? && ( report . coverage * 100 ) < threshold fail ( "Code coverage under minimum of #{threshold}%" ) end end


Input: Filters the files that haven t been modified in the current PR [CODESPLIT] def process_report ( report ) file_names = @dangerfile . git . modified_files . map { | file | File . basename ( file ) } file_names += @dangerfile . git . added_files . map { | file | File . basename ( file ) } report . targets . each do | target | target . files = target . files . select { | file | file_names . include? ( file . name ) } end report end


Input: Updates the CRC16 checksum . [CODESPLIT] def update ( data ) data . each_byte do | b | b = revert_byte ( b ) if REVERSE_DATA @crc = ( ( @table [ ( ( @crc >> 8 ) ^ b ) & 0xff ] ^ ( @crc << 8 ) ) & 0xffff ) end return self end


Input: class << self [CODESPLIT] def request ( http_verb , url , options = { } ) full_url = url + hash_to_params ( options ) handle ( access_token . request ( http_verb , full_url ) ) end


Input: Remove accents downcase replace spaces and word start with * return list of normalized words [CODESPLIT] def normalize ActiveSupport :: Multibyte :: Chars . new ( self ) . mb_chars . normalize ( :kd ) . gsub ( / \x00 \x7F / , '' ) . downcase . to_s . gsub ( / / , ' ' ) . gsub ( / \s / , '*' ) . gsub ( / / , '**' ) . gsub ( / / , '*' ) end


Input: Class macro used to associate an enum with an attribute on an ActiveRecord model . This method is added to an ActiveRecord model when ClassEnum :: ActiveRecord is included . Accepts an argument for the enum class to be associated with the model . ActiveRecord validation is automatically added to ensure that a value is one of its pre - defined enum members . [CODESPLIT] def classy_enum_attr ( attribute , options = { } ) enum = ( options [ :class_name ] || options [ :enum ] || attribute ) . to_s . camelize . constantize allow_blank = options [ :allow_blank ] || false allow_nil = options [ :allow_nil ] || false default = ClassyEnum . _normalize_default ( options [ :default ] , enum ) # Add ActiveRecord validation to ensure it won't be saved unless it's an option validates_inclusion_of attribute , in : enum , allow_blank : allow_blank , allow_nil : allow_nil # Use a module so that the reader methods can be overridden in classes and # use super to get the enum value. mod = Module . new do # Define getter method that returns a ClassyEnum instance define_method attribute do enum . build ( read_attribute ( attribute ) || super ( ) , owner : self ) end # Define setter method that accepts string, symbol, instance or class for member define_method "#{attribute}=" do | value | value = ClassyEnum . _normalize_value ( value , default , ( allow_nil || allow_blank ) ) super ( value ) end define_method :save_changed_attribute do | attr_name , arg | if attribute . to_s == attr_name . to_s && ! attribute_changed? ( attr_name ) arg = enum . build ( arg ) current_value = clone_attribute_value ( :read_attribute , attr_name ) if arg != current_value if respond_to? ( :set_attribute_was , true ) set_attribute_was ( attr_name , enum . build ( arg , owner : self ) ) else changed_attributes [ attr_name ] = enum . build ( current_value , owner : self ) end end else super ( attr_name , arg ) end end end include mod # Initialize the object with the default value if it is present # because this will let you store the default value in the # database and make it searchable. if default . present? after_initialize do value = read_attribute ( attribute ) || send ( attribute ) if ( value . blank? && ! ( allow_blank || allow_nil ) ) || ( value . nil? && ! allow_nil ) send ( "#{attribute}=" , default ) end end end end


Input: belows are data types [CODESPLIT] def string ( opts = { } ) length , any , value = ( opts [ :length ] || 8 ) , opts [ :any ] , opts [ :value ] if value string = value . to_s Proc . new { string } elsif any Proc . new { self . any ( any ) } else Proc . new { Array . new ( length ) { @chars [ rand ( @chars . size - 1 ) ] } . join } end end


Input: Delete an existing authorization . API calls using that token will stop working . API Path : / api / v2 / authorizations / : id == Parameters : id :: id [CODESPLIT] def authorization_delete ( id ) path = sprintf ( "/api/v2/authorizations/%s" , id ) data_hash = { } post_body = nil reqHelper = PhraseApp :: ParamsHelpers :: BodyTypeHelper . new ( data_hash , post_body ) rc , err = PhraseApp . send_request ( @credentials , "DELETE" , path , reqHelper . ctype , reqHelper . body , 204 ) if err != nil return nil , err end return err end


Input: Get details on a single authorization . API Path : / api / v2 / authorizations / : id == Parameters : id :: id [CODESPLIT] def authorization_show ( id ) path = sprintf ( "/api/v2/authorizations/%s" , id ) data_hash = { } post_body = nil reqHelper = PhraseApp :: ParamsHelpers :: BodyTypeHelper . new ( data_hash , post_body ) rc , err = PhraseApp . send_request ( @credentials , "GET" , path , reqHelper . ctype , reqHelper . body , 200 ) if err != nil return nil , err end return PhraseApp :: ResponseObjects :: Authorization . new ( JSON . load ( rc . body ) ) , err end


Input: Update an existing authorization . API Path : / api / v2 / authorizations / : id == Parameters : id :: id params :: Parameters of type PhraseApp :: RequestParams :: AuthorizationParams [CODESPLIT] def authorization_update ( id , params ) path = sprintf ( "/api/v2/authorizations/%s" , id ) data_hash = { } post_body = nil if params . present? unless params . kind_of? ( PhraseApp :: RequestParams :: AuthorizationParams ) raise PhraseApp :: ParamsHelpers :: ParamsError . new ( "Expects params to be kind_of PhraseApp::RequestParams::AuthorizationParams" ) end end data_hash = params . to_h err = params . validate if err != nil return nil , err end reqHelper = PhraseApp :: ParamsHelpers :: BodyTypeHelper . new ( data_hash , post_body ) rc , err = PhraseApp . send_request ( @credentials , "PATCH" , path , reqHelper . ctype , reqHelper . body , 200 ) if err != nil return nil , err end return PhraseApp :: ResponseObjects :: Authorization . new ( JSON . load ( rc . body ) ) , err end


Input: Get details on a single rule for blacklisting keys for a given project . API Path : / api / v2 / projects / : project_id / blacklisted_keys / : id == Parameters : project_id :: project_id id :: id [CODESPLIT] def blacklisted_key_show ( project_id , id ) path = sprintf ( "/api/v2/projects/%s/blacklisted_keys/%s" , project_id , id ) data_hash = { } post_body = nil reqHelper = PhraseApp :: ParamsHelpers :: BodyTypeHelper . new ( data_hash , post_body ) rc , err = PhraseApp . send_request ( @credentials , "GET" , path , reqHelper . ctype , reqHelper . body , 200 ) if err != nil return nil , err end return PhraseApp :: ResponseObjects :: BlacklistedKey . new ( JSON . load ( rc . body ) ) , err end


Input: Update an existing comment . API Path : / api / v2 / projects / : project_id / keys / : key_id / comments / : id == Parameters : project_id :: project_id key_id :: key_id id :: id params :: Parameters of type PhraseApp :: RequestParams :: CommentParams [CODESPLIT] def comment_update ( project_id , key_id , id , params ) path = sprintf ( "/api/v2/projects/%s/keys/%s/comments/%s" , project_id , key_id , id ) data_hash = { } post_body = nil if params . present? unless params . kind_of? ( PhraseApp :: RequestParams :: CommentParams ) raise PhraseApp :: ParamsHelpers :: ParamsError . new ( "Expects params to be kind_of PhraseApp::RequestParams::CommentParams" ) end end data_hash = params . to_h err = params . validate if err != nil return nil , err end reqHelper = PhraseApp :: ParamsHelpers :: BodyTypeHelper . new ( data_hash , post_body ) rc , err = PhraseApp . send_request ( @credentials , "PATCH" , path , reqHelper . ctype , reqHelper . body , 200 ) if err != nil return nil , err end return PhraseApp :: ResponseObjects :: Comment . new ( JSON . load ( rc . body ) ) , err end


Input: List all glossaries the current user has access to . API Path : / api / v2 / accounts / : account_id / glossaries == Parameters : account_id :: account_id [CODESPLIT] def glossaries_list ( account_id , page , per_page ) path = sprintf ( "/api/v2/accounts/%s/glossaries" , account_id ) data_hash = { } post_body = nil reqHelper = PhraseApp :: ParamsHelpers :: BodyTypeHelper . new ( data_hash , post_body ) rc , err = PhraseApp . send_request_paginated ( @credentials , "GET" , path , reqHelper . ctype , reqHelper . body , 200 , page , per_page ) if err != nil return nil , err end return JSON . load ( rc . body ) . map { | item | PhraseApp :: ResponseObjects :: Glossary . new ( item ) } , err end


Input: Create a new glossary . API Path : / api / v2 / accounts / : account_id / glossaries == Parameters : account_id :: account_id params :: Parameters of type PhraseApp :: RequestParams :: GlossaryParams [CODESPLIT] def glossary_create ( account_id , params ) path = sprintf ( "/api/v2/accounts/%s/glossaries" , account_id ) data_hash = { } post_body = nil if params . present? unless params . kind_of? ( PhraseApp :: RequestParams :: GlossaryParams ) raise PhraseApp :: ParamsHelpers :: ParamsError . new ( "Expects params to be kind_of PhraseApp::RequestParams::GlossaryParams" ) end end data_hash = params . to_h err = params . validate if err != nil return nil , err end reqHelper = PhraseApp :: ParamsHelpers :: BodyTypeHelper . new ( data_hash , post_body ) rc , err = PhraseApp . send_request ( @credentials , "POST" , path , reqHelper . ctype , reqHelper . body , 201 ) if err != nil return nil , err end return PhraseApp :: ResponseObjects :: Glossary . new ( JSON . load ( rc . body ) ) , err end


Input: Get details on a single glossary . API Path : / api / v2 / accounts / : account_id / glossaries / : id == Parameters : account_id :: account_id id :: id [CODESPLIT] def glossary_show ( account_id , id ) path = sprintf ( "/api/v2/accounts/%s/glossaries/%s" , account_id , id ) data_hash = { } post_body = nil reqHelper = PhraseApp :: ParamsHelpers :: BodyTypeHelper . new ( data_hash , post_body ) rc , err = PhraseApp . send_request ( @credentials , "GET" , path , reqHelper . ctype , reqHelper . body , 200 ) if err != nil return nil , err end return PhraseApp :: ResponseObjects :: Glossary . new ( JSON . load ( rc . body ) ) , err end


Input: Get details on a single glossary term . API Path : / api / v2 / accounts / : account_id / glossaries / : glossary_id / terms / : id == Parameters : account_id :: account_id glossary_id :: glossary_id id :: id [CODESPLIT] def glossary_term_show ( account_id , glossary_id , id ) path = sprintf ( "/api/v2/accounts/%s/glossaries/%s/terms/%s" , account_id , glossary_id , id ) data_hash = { } post_body = nil reqHelper = PhraseApp :: ParamsHelpers :: BodyTypeHelper . new ( data_hash , post_body ) rc , err = PhraseApp . send_request ( @credentials , "GET" , path , reqHelper . ctype , reqHelper . body , 200 ) if err != nil return nil , err end return PhraseApp :: ResponseObjects :: GlossaryTerm . new ( JSON . load ( rc . body ) ) , err end


Input: Update an existing glossary term . API Path : / api / v2 / accounts / : account_id / glossaries / : glossary_id / terms / : id == Parameters : account_id :: account_id glossary_id :: glossary_id id :: id params :: Parameters of type PhraseApp :: RequestParams :: GlossaryTermParams [CODESPLIT] def glossary_term_update ( account_id , glossary_id , id , params ) path = sprintf ( "/api/v2/accounts/%s/glossaries/%s/terms/%s" , account_id , glossary_id , id ) data_hash = { } post_body = nil if params . present? unless params . kind_of? ( PhraseApp :: RequestParams :: GlossaryTermParams ) raise PhraseApp :: ParamsHelpers :: ParamsError . new ( "Expects params to be kind_of PhraseApp::RequestParams::GlossaryTermParams" ) end end data_hash = params . to_h err = params . validate if err != nil return nil , err end reqHelper = PhraseApp :: ParamsHelpers :: BodyTypeHelper . new ( data_hash , post_body ) rc , err = PhraseApp . send_request ( @credentials , "PATCH" , path , reqHelper . ctype , reqHelper . body , 200 ) if err != nil return nil , err end return PhraseApp :: ResponseObjects :: GlossaryTerm . new ( JSON . load ( rc . body ) ) , err end


Input: Update an existing job locale . API Path : / api / v2 / projects / : project_id / jobs / : job_id / locales / : id == Parameters : project_id :: project_id job_id :: job_id id :: id params :: Parameters of type PhraseApp :: RequestParams :: JobLocaleParams [CODESPLIT] def job_locale_update ( project_id , job_id , id , params ) path = sprintf ( "/api/v2/projects/%s/jobs/%s/locales/%s" , project_id , job_id , id ) data_hash = { } post_body = nil if params . present? unless params . kind_of? ( PhraseApp :: RequestParams :: JobLocaleParams ) raise PhraseApp :: ParamsHelpers :: ParamsError . new ( "Expects params to be kind_of PhraseApp::RequestParams::JobLocaleParams" ) end end data_hash = params . to_h err = params . validate if err != nil return nil , err end reqHelper = PhraseApp :: ParamsHelpers :: BodyTypeHelper . new ( data_hash , post_body ) rc , err = PhraseApp . send_request ( @credentials , "PATCH" , path , reqHelper . ctype , reqHelper . body , 200 ) if err != nil return nil , err end return PhraseApp :: ResponseObjects :: JobLocale . new ( JSON . load ( rc . body ) ) , err end


Input: List all job locales for a given job . API Path : / api / v2 / projects / : project_id / jobs / : job_id / locales == Parameters : project_id :: project_id job_id :: job_id params :: Parameters of type PhraseApp :: RequestParams :: JobLocalesListParams [CODESPLIT] def job_locales_list ( project_id , job_id , page , per_page , params ) path = sprintf ( "/api/v2/projects/%s/jobs/%s/locales" , project_id , job_id ) data_hash = { } post_body = nil if params . present? unless params . kind_of? ( PhraseApp :: RequestParams :: JobLocalesListParams ) raise PhraseApp :: ParamsHelpers :: ParamsError . new ( "Expects params to be kind_of PhraseApp::RequestParams::JobLocalesListParams" ) end end data_hash = params . to_h err = params . validate if err != nil return nil , err end reqHelper = PhraseApp :: ParamsHelpers :: BodyTypeHelper . new ( data_hash , post_body ) rc , err = PhraseApp . send_request_paginated ( @credentials , "GET" , path , reqHelper . ctype , reqHelper . body , 200 , page , per_page ) if err != nil return nil , err end return JSON . load ( rc . body ) . map { | item | PhraseApp :: ResponseObjects :: JobLocale . new ( item ) } , err end