Input: Adds source files to the group Seeds and save its reference to { #file_references } and removes disused sources files [CODESPLIT] def configure_project say "Configuring #{self.project.path.basename}" group = self . project [ "Seeds" ] if group group . clear else uuid = Xcodeproj :: uuid_with_name "Seeds" group = self . project . new_group_with_uuid ( "Seeds" , uuid ) end # remove existing group that doesn't have any file references group . groups . each do | seedgroup | valid_files = seedgroup . children . select do | child | File . exist? ( child . real_path ) end if valid_files . length == 0 seedgroup . remove_from_project end end self . source_files . each do | seedname , filepaths | uuid = Xcodeproj :: uuid_with_name "Seeds/#{seedname}" seedgroup = group [ seedname ] || group . new_group_with_uuid ( seedname , uuid ) filepaths . each do | path | filename = path . split ( '/' ) [ - 1 ] relpath = path [ self . root_path . length .. - 1 ] uuid = Xcodeproj :: uuid_with_name relpath file_reference = seedgroup [ filename ] || seedgroup . new_reference_with_uuid ( path , uuid ) self . file_references << file_reference end unusing_files = seedgroup . files - self . file_references unusing_files . each { | file | file . remove_from_project } end end


Input: Adds file references to the Sources Build Phase . [CODESPLIT] def configure_phase self . project . targets . each do | target | begin phase = target . sources_build_phase # support resources phase resource_phase = target . resources_build_phase next unless phase rescue NoMethodError next end # remove zombie build files phase . files_references . each do | file | begin file . real_path rescue phase . files . each do | build_file | phase . files . delete ( build_file ) if build_file . file_ref == file end end end resource_phase . files_references . each do | file | begin file . real_path rescue resource_phase . files . each do | build_file | resource_phase . files . delete ( build_file ) if build_file . file_ref == file end end end removings = [ ] # name of seeds going to be removed from the target addings = [ ] # name of seeds going to be added to the target self . targets . keys . sort . each do | seed_name | target_names = self . targets [ seed_name ] if not target_names . include? ( target . name ) removings << seed_name if not removings . include? ( seed_name ) else addings << seed_name if not addings . include? ( seed_name ) end end self . file_references . each do | file | removings . each do | seed_names | next if not seed_names . include? ( file . parent . name ) phase . files . each do | build_file | phase . files . delete ( build_file ) if build_file . file_ref == file end resource_phase . files . each do | build_file | resource_phase . files . delete ( build_file ) if build_file . file_ref == file end end addings . each do | seed_names | next if file . name . end_with? ".h" next if not seed_names . include? ( file . parent . name ) uuid = Xcodeproj :: uuid_with_name "#{target.name}:#{file.name}" # Treat a file as resource file unless confirm it can be compiled. if self . valid_source_file? ( file ) phase . add_file_reference_with_uuid ( file , uuid , true ) else resource_phase . add_file_reference_with_uuid ( file , uuid , true ) end end end end end


Input: Determines whether there s a source file . [CODESPLIT] def valid_source_file? filename suffixs = [ ".h" , ".c" , ".m" , ".mm" , ".swift" , ".cpp" ] suffixs . each do | suffix | return true if filename . name . end_with? suffix end return false end


Input: Writes Seedfile . lock file . [CODESPLIT] def build_lockfile tree = { "SEEDS" => [ ] } self . seeds . each do | name , seed | if not seed . instance_of? Seeds :: Seed :: LocalSeed tree [ "SEEDS" ] << "#{name} (#{seed.version or '$' + seed.commit})" end end File . write ( self . lockfile_path , YAML . dump ( tree ) ) end


Input: create an Aspell speller object [CODESPLIT] def speller return @speller if @speller # raspell is an optional dependency, handle the missing case nicely begin require "raspell" rescue LoadError $stderr . puts "ERROR: Ruby gem \"raspell\" is not installed." exit 1 end # initialize aspell @speller = Aspell . new ( "en_US" ) @speller . suggestion_mode = Aspell :: NORMAL # ignore the HTML tags in the text @speller . set_option ( "mode" , "html" ) @speller end


Input: evaluate the files to check [CODESPLIT] def files_to_check files = config [ "check" ] . reduce ( [ ] ) { | a , e | a + Dir [ e ] } config [ "ignore" ] . reduce ( files ) { | a , e | a - Dir [ e ] } end


Input: read a Yaml config file [CODESPLIT] def read_spell_config ( file ) return { } unless File . exist? ( file ) puts "Loading config file (#{file})..." if verbose == true require "yaml" YAML . load_file ( file ) end


Input: print the duplicate dictionary entries [CODESPLIT] def report_duplicates ( dict1 , dict2 ) duplicates = dict1 & dict2 return if duplicates . empty? $stderr . puts "Warning: Found dictionary duplicates in the local dictionary " "(#{CUSTOM_SPELL_CONFIG_FILE}):\n" duplicates . each { | duplicate | $stderr . puts "  #{duplicate}" } $stderr . puts end


Input: return the merged global and the custom spell configs [CODESPLIT] def config return @config if @config @config = read_spell_config ( GLOBAL_SPELL_CONFIG_FILE ) custom_config = read_spell_config ( CUSTOM_SPELL_CONFIG_FILE ) report_duplicates ( config [ "dictionary" ] , custom_config [ "dictionary" ] . to_a ) custom_config [ "dictionary" ] = @config [ "dictionary" ] + custom_config [ "dictionary" ] . to_a custom_config [ "dictionary" ] . uniq! # override the global values by the local if present @config . merge! ( custom_config ) @config end


Input: check the file using the spellchecker [CODESPLIT] def check_file ( file ) puts "Checking #{file}..." if verbose == true # spell check each line separately so we can report error locations properly lines = File . read ( file ) . split ( "\n" ) success = true lines . each_with_index do | text , index | misspelled = misspelled_on_line ( text ) next if misspelled . empty? success = false print_misspelled ( misspelled , index , text ) end success end


Input: Execute a rake / capistrano task only for given server [CODESPLIT] def invoke_for_server ( server , task , * args ) backup_filter = fetch :filter , { } new_server_filter = Marshal . load ( Marshal . dump ( backup_filter ) ) new_server_filter [ :host ] = server . hostname set :filter , new_server_filter env . setup_filters info I18n . t ( 'dsl.invoke_for_server.set_filter' , task : task , host : server . hostname , scope : :dkdeploy ) invoke! task , args ensure set :filter , backup_filter env . setup_filters end


Input: @param [ OptBase ] opt [CODESPLIT] def opt_help_messages ( opt ) opt . help_messages . empty? ? [ opt . to_s . humanize ] : opt . help_messages end


Input: @param [ String ] value [CODESPLIT] def validate ( value ) results = { } super ( value ) . each do | item | opt = choices [ item . to_sym ] if opt opt_value = opt . value_if_empty . nil? ? true : opt . value_if_empty else opt , opt_value = value_from_pattern ( item ) end results [ opt . to_sym ] = opt . normalize ( opt . validate ( opt_value ) ) end verify_compatibility ( results ) end


Input: @param [ Hash ] values [CODESPLIT] def verify_compatibility ( values ) incompatible . each do | a | last_match = '' a . each do | key | sym = choices [ key ] . to_sym next unless values . key? ( sym ) raise Error , "Incompatible choices detected: #{last_match}, #{key}" unless last_match . empty? last_match = key end end values end


Input: @param [ String ] value [CODESPLIT] def validate ( value ) a = super ( value ) . split ( separator ) raise Error , "Incorrect number of ranges found: #{a.size}, should be 2" unless a . size == 2 first_integer = a . first . to_i last_integer = a . last . to_i raise Error , 'Argument is not a valid integer range' unless first_integer . to_s == a . first && last_integer . to_s == a . last ( first_integer .. last_integer ) end


Input: See OptBase#normalize [CODESPLIT] def normalize ( values ) values . each_with_index do | value , index | values [ index ] = super ( value ) end values end


Input: Initialize attrs : [CODESPLIT] def validate ( value ) path = Pathname . new ( value ) allowed_attrs . each do | key | method = "check_#{key}" send ( method , path ) if respond_to? ( method ) && attrs [ key ] end path . to_s end


Input: If the path does not exist it will check for the parent directory write permission [CODESPLIT] def check_writable ( path ) raise Error , "'#{path}' is not writable" if path . exist? && ! path . writable? || ! path . parent . writable? end


Input: @param [ Array ] option See OptionParser#on @param [ Hash ] attrs @option attrs [ Boolean ] : required @options attrs [ Array<Symbol > Symbol ] : required_unless @option attrs [ Mixed ] : default The default value to use if the option is not supplied @option attrs [ Mixed ] : value_if_empty The value to use if no argument has been supplied @option attrs [ Array<Symbol > ] : normalize See #normalize [CODESPLIT] def append_help_messages option << "Default: #{help_message_for_default}" if default option << "Value if no argument supplied: #{value_if_empty}" if value_if_empty option << 'This option is mandatory' if required? option << "This option is mandatory unless #{required_unless.join(' or ')} is/are supplied" unless required_unless . empty? end


Input: Apply each methods from attrs [ : normalize ] to the value if possible User input should not be used in this attrs [ : normalize ] [CODESPLIT] def normalize ( value ) [ attrs [ :normalize ] ] . each do | method | next unless method . is_a? ( Symbol ) value = value . send ( method ) if value . respond_to? ( method ) end value end


Input: @param [ Array<OptBase > ] options [CODESPLIT] def add ( * options ) options . each do | option | check_option ( option ) @opts << option @symbols_used << option . to_sym # Set the default option value if it exists # The default value is not validated as it is provided by devs # and should be set to the correct format/value directly @results [ option . to_sym ] = option . default unless option . default . nil? register_callback ( option ) end self end


Input: Ensures the opt given is valid [CODESPLIT] def check_option ( opt ) raise Error , "The option is not an OptBase, #{opt.class} supplied" unless opt . is_a? ( OptBase ) raise Error , "The option #{opt.to_sym} is already used !" if @symbols_used . include? ( opt . to_sym ) end


Input: @param [ OptBase ] opt [CODESPLIT] def register_callback ( opt ) on ( opt . option ) do | arg | begin if opt . alias? parse! ( opt . alias_for . split ( ' ' ) ) else @results [ opt . to_sym ] = opt . normalize ( opt . validate ( arg ) ) end rescue StandardError => e # Adds the long option name to the message # And raises it as an OptParseValidator::Error if not already one # e.g --proxy Invalid Scheme format. raise e . is_a? ( Error ) ? e . class : Error , "#{opt.to_long} #{e}" end end end


Input: Ensure that all required options are supplied Should be overriden to modify the behavior [CODESPLIT] def post_processing @opts . each do | opt | raise NoRequiredOption , "The option #{opt} is required" if opt . required? && ! @results . key? ( opt . to_sym ) next if opt . required_unless . empty? || @results . key? ( opt . to_sym ) fail_msg = "One of the following options is required: #{opt}, #{opt.required_unless.join(', ')}" raise NoRequiredOption , fail_msg unless opt . required_unless . any? do | sym | @results . key? ( sym ) end end end


Input: @param [ String ] value [CODESPLIT] def validate ( value ) values = super ( value ) . chomp ( ';' ) . split ( '; ' ) headers = { } values . each do | header | raise Error , "Malformed header: '#{header}'" unless header . index ( ':' ) val = header . split ( ':' , 2 ) headers [ val [ 0 ] . strip ] = val [ 1 ] . strip end headers end


Input: @param [ String ] value [CODESPLIT] def validate ( value ) uri = Addressable :: URI . parse ( value ) uri = Addressable :: URI . parse ( "#{default_protocol}://#{value}" ) if ! uri . scheme && default_protocol unless allowed_protocols . empty? || allowed_protocols . include? ( uri . scheme &. downcase ) # For future refs: will have to check if the uri.scheme exists, # otherwise it means that the value was empty raise Addressable :: URI :: InvalidURIError end uri . to_s end


Input: @param [ String ] file_path [CODESPLIT] def << ( file_path ) return self unless File . exist? ( file_path ) ext = File . extname ( file_path ) . delete ( '.' ) raise Error , "The option file's extension '#{ext}' is not supported" unless self . class . supported_extensions . include? ( ext ) super ( ConfigFile . const_get ( ext . upcase ) . new ( file_path ) ) end


Input: @params [ Hash ] opts @option opts [ Boolean ] : symbolize_keys Whether or not to symbolize keys in the returned hash @option opts [ Array ] : yaml_arguments See https : // ruby - doc . org / stdlib - 2 . 3 . 1 / libdoc / psych / rdoc / Psych . html#method - c - safe_load [CODESPLIT] def parse ( opts = { } ) result = { } each { | option_file | result . deep_merge! ( option_file . parse ( opts ) ) } opts [ :symbolize_keys ] ? result . deep_symbolize_keys : result end


Input: @param [ String ] value [CODESPLIT] def validate ( value ) raise Error , "#{value} is not an integer" if value . to_i . to_s != value value . to_i end


Input: Conversions Get entities of files in dir [CODESPLIT] def subdir_entities ( dir = @current_dir ) Dir . glob ( dir [ :path ] . gsub ( / \\ \[ \] / , '\\\\\0' ) + '/*' ) . map! { | path | { path : path , time : File . mtime ( path ) , name : File . basename ( path ) } } end


Input: Fix an entity : time - > DOSTime object name - > abs path in zip & encoded [CODESPLIT] def fix_entity ( entity ) { path : entity [ :path ] , filetime : Zip :: DOSTime . at ( entity [ :time ] || File . mtime ( entity [ :path ] ) ) , binary_name : string_to_bytes ( abs_path_for_entity ( entity ) ) , zip_path : abs_path_for_entity ( entity ) } end


Input: Create ASCII - 8bits string . Also convert encoding if needed . [CODESPLIT] def string_to_bytes ( str ) unless @e . nil? || @e == :utf8 if @e == :shift_jis begin str = str . gsub / \\ \uff5e / , '？' str . encode! 'Shift_JIS' , :invalid => :replace , :undef => :replace , :replace => '？' rescue => e end end end [ str ] . pack ( 'a*' ) end


Input: Compression operations Pack file and directory entities and output to stream . [CODESPLIT] def pack ( files ) entities = Entity . entities_from files return if entities . empty? reset_state pack_entities entities while has_dir? cd next_dir pack_current_dir end end


Input: Pack symlinks if its link path exists in zip [CODESPLIT] def pack_symlinks reset_state @l . each do | link | if @w . path_exists? Entity . linked_path ( link [ :abs_path ] , File . readlink ( link [ :path ] ) ) link [ :name ] = link [ :abs_path ] pack_symbolic_link_entity link end end end


Input: Pack file entities . Directory entities are queued not packed in this method . [CODESPLIT] def pack_entities ( entities ) entities . each do | entity | # ignore bad entities next unless entity . is_a? ( Hash ) && entity [ :path ] path = entity [ :path ] if File . symlink? path postpone_symlink entity elsif File . directory? path postpone_dir entity elsif File . file? path pack_file_entity entity end end end


Input: Write operations [CODESPLIT] def write_file_entry write_entry do | path , filetime , name | write PKHeader . pk0304 ( filetime , name . length , true ) . pack ( 'VvvvvvVVVvv' ) , name ret = deflate_file path write PKHeader . pk0708 ( ret [ :crc ] , ret [ :complen ] , ret [ :uncomplen ] ) . pack ( 'VVVV' ) ret end end


Input: rubocop : disable Metrics / ParameterLists rubocop : enable Metrics / ParameterLists : reek : TooManyStatements [CODESPLIT] def activatable? attributes = { } return false unless search_value . present? attributes = attributes . with_indifferent_access current_search_value = attributes [ search_key ] if current_search_value . is_a? ( Regexp ) || search_value . is_a? ( Regexp ) return false if current_search_value . blank? current_search_value . match? search_value else current_search_value == search_value end end


Input: rubocop : disable Metrics / LineLength [CODESPLIT] def activate attributes = { } attributes = attributes . with_indifferent_access attributes [ target_key ] = [ attributes [ target_key ] , target_value ] . compact . join " " if activatable? attributes attributes end


Input: rubocop : enable Metrics / LineLength [CODESPLIT] def add name , content = nil , attributes : { } , activator : menu_activator , & block tag = Navigator :: Tag . new name , content , attributes : attributes , activator : activator return items << tag . render unless block_given? items << tag . prefix items << tag . content instance_eval ( block ) items << tag . suffix end


Input: rubocop : disable Metrics / ParameterLists rubocop : disable Metrics / LineLength [CODESPLIT] def navigation tag = "ul" , attributes : { } , activator : navigation_activator , & block raw Navigator :: Menu . new ( self , tag : tag , attributes : attributes , activator : activator , block ) . render end


Input: Render html tag [CODESPLIT] def render content_tag :div , @html_options do concat content_tag ( :div , table_name , class : 'title' ) concat TableSearchField . new ( { store : @store , wrap_form : @options [ :wrap_form ] } ) . render if searchable? concat tag :br , class : 'ui-bibz-clear' end end


Input: See UiBibz :: Ui :: Core :: Component . initialize Render html tag [CODESPLIT] def pre_render if options [ :nav_type ] == "nav-links" UiBibz :: Ui :: Core :: Navigations :: NavLinkLink . new ( content , options , html_options ) . render else if options [ :tag_type ] == :span cont = UiBibz :: Ui :: Core :: Navigations :: NavLinkSpan . new ( content , @old_options ) . render else cont = UiBibz :: Ui :: Core :: Navigations :: NavLinkLink . new ( content , options ) . render end #html_options[:class] = remove_class(html_options[:class]) remove_classes UiBibz :: Ui :: Core :: Navigations :: NavLinkList . new ( cont , options , html_options ) . render end end


Input: See UiBibz :: Ui :: Core :: Component . initialize Render html tag [CODESPLIT] def pre_render content_tag tag_type , html_options do concat glyph_and_content_html if @content concat header_html if @body concat body_html if @body concat badge_html if @options [ :badge ] end end


Input: Add header which is a component [CODESPLIT] def header content = nil , options = nil , html_options = nil , & block @header = UiBibz :: Ui :: Core :: Lists :: Components :: ListHeader . new content , options , html_options , block end


Input: Add body which is a component [CODESPLIT] def body content = nil , options = nil , html_options = nil , & block @body = UiBibz :: Ui :: Core :: Lists :: Components :: ListBody . new content , options , html_options , block end


Input: Add group list See UiBibz :: Ui :: Core :: List [CODESPLIT] def list content = nil , options = { } , html_options = nil , & block options = options . merge ( { tag_type : @options [ :tag_type ] } ) unless @options [ :tag_type ] . nil? if is_tap ( content , options ) @lists << UiBibz :: Ui :: Core :: Lists :: Components :: List . new ( content , options , html_options ) . tap ( block ) . render else @lists << UiBibz :: Ui :: Core :: Lists :: Components :: List . new ( content , options , html_options , block ) . render end end


Input: See UiBibz :: Ui :: Core :: Component . initialize [CODESPLIT] def pre_render content_tag :div , html_options do concat UiBibz :: Ui :: Core :: Icons :: Glyph . new ( options [ :glyph ] , class : 'mr-2' ) . render unless options [ :glyph ] . nil? concat image_tag ( options [ :img ] , class : 'rounded mr-2' ) unless options [ :img ] . nil? concat content_tag ( :strong , content , class : 'mr-auto' ) concat content_tag ( :small , options [ :time ] , class : 'text-muted' ) unless options [ :time ] . nil? concat close_button end end


Input: See UiBibz :: Ui :: Core :: Component . initialize Render html tag [CODESPLIT] def pre_render content_tag :div , html_options do concat file_field_tag content , class : "custom-file-input" , multiple : options [ :multiple ] , disabled : is_disabled? concat label_tag label_name , label_content , class : 'custom-file-label' end end


Input: See UiBibz :: Ui :: Core :: Forms :: Choices :: Button . initialize [CODESPLIT] def choice content = nil , opts = nil , html_options = nil , & block if block . nil? opts = @options . merge ( opts || { } ) else content = @options . merge ( content || { } ) end @items << Choice . new ( content , opts , html_options , block ) . render end


Input: Maybe create a class for td_content [CODESPLIT] def td_content record , col content = col . count ? record . send ( col . data_index ) . count : record . send ( col . data_index ) unless content . nil? content = content . strftime ( col . date_format ) unless col . date_format . nil? content = link_to content , action . inject_url ( col . link , record ) unless col . link . nil? content = col . format . call ( @store . records , record ) unless col . format . nil? end content = As . new ( col , record , content , @options ) . render unless col . as . nil? content end


Input: Add Header which is a component [CODESPLIT] def header content = nil , options = nil , html_options = nil , & block @header = UiBibz :: Ui :: Core :: Notifications :: Components :: ToastHeader . new ( content , options , html_options , block ) . render end


Input: See UiBibz :: Ui :: Core :: Component . initialize Add Header which is a component [CODESPLIT] def header content = nil , options = nil , html_options = nil , & block options , content = inherit_options ( content , options , block ) if is_tap ( content , options ) @header = UiBibz :: Ui :: Core :: Boxes :: Components :: CardHeader . new ( content , options , html_options ) . tap ( block ) . render else @header = UiBibz :: Ui :: Core :: Boxes :: Components :: CardHeader . new ( content , options , html_options , block ) . render end end


Input: Add Body div which is a component [CODESPLIT] def body content = nil , options = nil , html_options = nil , & block options , content = inherit_options ( content , options , block ) if is_tap ( content , options ) content = ( content || { } ) . merge ( collapse : options . try ( :[] , :collapse ) , parent_collapse : @options [ :parent_collapse ] ) @items << UiBibz :: Ui :: Core :: Boxes :: Components :: CardBody . new ( content , options , html_options ) . tap ( block ) . render else options = ( options || { } ) . merge ( collapse : options . try ( :[] , :collapse ) , parent_collapse : @options [ :parent_collapse ] ) @items << UiBibz :: Ui :: Core :: Boxes :: Components :: CardBody . new ( content , options , html_options , block ) . render end end


Input: Add Footer which is a component [CODESPLIT] def footer content = nil , options = nil , html_options = nil , & block options , content = inherit_options ( content , options , block ) @footer = UiBibz :: Ui :: Core :: Boxes :: Components :: CardFooter . new ( content , options , html_options , block ) . render end


Input: Add List group which is a component [CODESPLIT] def list_group content = nil , options = nil , html_options = nil , & block @items << UiBibz :: Ui :: Core :: Boxes :: Components :: CardListGroup . new ( content , options , html_options ) . tap ( block ) . render end


Input: Add Image which is a component [CODESPLIT] def image content = nil , options = nil , html_options = nil , & block @items << UiBibz :: Ui :: Core :: Boxes :: Components :: CardImage . new ( content , options , html_options , block ) . render end


Input: See UiBibz :: Ui :: Core :: Component . initialize Render html tag [CODESPLIT] def pre_render content_tag :nav , html_options do concat title if brand_position == :left concat navbar_toggle_button_html concat title if brand_position == :right concat body_html end end


Input: Add navbar nav items See UiBibz :: Ui :: Core :: NavbarNav [CODESPLIT] def nav content = nil , options = nil , html_options = nil , & block options = options || { } @items << UiBibz :: Ui :: Core :: Navigations :: NavbarNav . new ( content , options , html_options ) . tap ( block ) end


Input: Add navbar form items See UiBibz :: Ui :: Core :: NavbarForm [CODESPLIT] def form model_or_url , options = { } , & block @items << UiBibz :: Ui :: Core :: Navigations :: NavbarForm . new ( model_or_url , options , block ) end


Input: Not use !!!!! Add navbar text items See UiBibz :: Ui :: Core :: NavbarText [CODESPLIT] def text content = nil , options = nil , html_options = nil , & block @items << UiBibz :: Ui :: Core :: Navigations :: NavbarText . new ( content , options , html_options , block ) end


Input: See UiBibz :: Ui :: Core :: Component . initialize Add nav link items See UiBibz :: Ui :: Core :: Navigations :: NavLink [CODESPLIT] def tab content = nil , options = { } , html_options = nil , & block block_given? ? content . merge! ( { nav_type : type , tag_type : @options [ :tag_type ] } ) : options . merge! ( { nav_type : type , tag_type : @options [ :tag_type ] } ) @items << NavLink . new ( content , options , html_options , block ) end


Input: Add breadcrumb link items See UiBibz :: Ui :: Core :: BreadcrumbLink [CODESPLIT] def link content = nil , options = nil , html_options = nil , & block @links << UiBibz :: Ui :: Core :: Navigations :: Components :: BreadcrumbLink . new ( content , options , html_options , block ) . render end


Input: See UiBibz :: Ui :: Core :: Component . initialize Render html tag [CODESPLIT] def pre_render output = [ content_tag ( :p , content , html_options ) ] output << content_tag ( :small , options [ :extra ] ) output . join . html_safe end


Input: include WillPaginate :: ActionView :: BootstrapLinkRenderer Initialize pagination with component item pagination require WillPaginate gem Render html tag with boostrap pagination theme [CODESPLIT] def render paginate_parameters = { controller : store . controller } paginate_parameters = paginate_parameters . merge ( { store_id : store . id } ) unless store . id . nil? paginate_parameters = paginate_parameters . merge ( store . parameters ) paginate_parameters = paginate_parameters . merge ( { link_type : 'pagination' } ) will_paginate ( store . records , params : paginate_parameters . with_indifferent_access . reject { | k , v | default_parameters? ( k ) || v . blank? } , renderer : WillPaginate :: ActionView :: BootstrapLinkRenderer ) end


Input: Render html tag [CODESPLIT] def render content_tag :div , @html_options do concat UiBibz :: Ui :: Ux :: Tables :: TablePagination . new ( store : @store , wrap_form : @options [ :wrap_form ] ) . render concat UiBibz :: Ui :: Ux :: Tables :: TablePaginationPerPage . new ( store : @store , wrap_form : @options [ :wrap_form ] ) . render concat tag ( :br , class : 'ui-bibz-clear' ) end end


Input: Add html component [CODESPLIT] def html content = nil , & block if ! block . nil? context = eval ( "self" , block . binding ) @items << context . capture ( block ) else @items << content end end


Input: See UiBibz :: Ui :: Core :: Boxes :: Component . initialize Render html tag [CODESPLIT] def pre_render content_tag :div , html_options do if fluid UiBibz :: Ui :: Core :: Layouts :: Container . new ( content ) . render else content end end end


Input: Try to put it on a line [CODESPLIT] def component_html_options super . merge ( { multiple : options [ :multiple ] , disabled : options [ :state ] == :disabled , include_blank : options [ :include_blank ] , prompt : options [ :prompt ] } ) end


Input: Add nav link items See UiBibz :: Ui :: Core :: Navigations :: NavLink [CODESPLIT] def link content = nil , options = { } , html_options = nil , & block block_given? ? content . merge! ( { nav_type : type } ) : options . merge! ( { nav_type : type } ) @items << NavLink . new ( content , options , html_options , block ) end


Input: Add nav in nav [CODESPLIT] def nav content = nil , options = { } , html_options = nil , & block @items << UiBibz :: Ui :: Core :: Component . new ( Nav . new ( content , options ) . tap ( block ) . render , { } , html_options ) end


Input: Add nav dropdown items See UiBibz :: Ui :: Core :: Navigations :: NavDropdown [CODESPLIT] def dropdown content = nil , options = { } , html_options = nil , & block @items << NavDropdown . new ( content , options , html_options ) . tap ( block ) end


Input: Add nav link items See UiBibz :: Ui :: Core :: Navigations :: NavLink [CODESPLIT] def link content = nil , options = { } , html_options = nil , & block @items << PaginationLink . new ( content , options , html_options , block ) . render end


Input: Add Header which is a component [CODESPLIT] def header content = nil , options = nil , html_options = nil , & block if block . nil? options = @options . merge ( options || { } ) else content = @options . merge ( content || { } ) end @header = UiBibz :: Ui :: Core :: Notifications :: Components :: AlertHeader . new ( content , options , html_options , block ) . render end


Input: Add Body which is a component [CODESPLIT] def body content = nil , options = nil , html_options = nil , & block @body = UiBibz :: Ui :: Core :: Notifications :: Components :: AlertBody . new ( content , options , html_options , block ) . render end


Input: See UiBibz :: Ui :: Core :: Component . initialize Render html tag [CODESPLIT] def pre_render if options [ :collapse ] content_tag :div , class : join_classes ( "collapse" , show ) , id : options [ :collapse ] , "data-parent" : "##{ options[:parent_collapse] }" do content_tag :div , @items . join . html_safe , html_options end else content_tag :div , @items . join . html_safe , html_options end end


Input: Know if component is tapped or not [CODESPLIT] def is_tap content , options ( content [ :tap ] if content . kind_of? ( Hash ) ) || ( options [ :tap ] unless options . nil? ) end


Input: Override this method to add html data [CODESPLIT] def component_html_data # To stimulusjs data_target = html_options . try ( :[] , :data ) . try ( :[] , :target ) || options . try ( :delete , :target ) add_html_data ( :target , data_target ) unless data_target . nil? data_controller = html_options . try ( :[] , :data ) . try ( :[] , :controller ) || options . try ( :delete , :controller ) add_html_data ( :controller , data_controller ) unless data_controller . nil? data_action = html_options . try ( :[] , :data ) . try ( :[] , :action ) || options . try ( :delete , :action ) add_html_data ( :action , data_action ) unless data_action . nil? # To turbolinks data_turbolinks = html_options . try ( :[] , :data ) . try ( :[] , :turbolinks ) || options . try ( :delete , :turbolinks ) add_html_data ( :turbolinks , data_turbolinks ) unless data_turbolinks . nil? end


Input: Add html data arguments [CODESPLIT] def add_html_data name , value = true html_options [ :data ] = { } if html_options [ :data ] . nil? value = value . kind_of? ( String ) ? value . strip : value html_options [ :data ] . update ( Hash [ name , value ] ) end


Input: Add Header which is a component [CODESPLIT] def header content = nil , options = nil , html_options = nil , & block if is_tap ( content , options ) @header = UiBibz :: Ui :: Ux :: Containers :: Components :: PanelHeader . new ( content , options , html_options ) . tap ( block ) . render else @header = UiBibz :: Ui :: Ux :: Containers :: Components :: PanelHeader . new ( content , options , html_options , block ) . render end end


Input: Add Header which is a component [CODESPLIT] def footer content = nil , options = nil , html_options = nil , & block if is_tap ( content , options ) @footer = UiBibz :: Ui :: Ux :: Containers :: Components :: PanelFooter . new ( content , options , html_options ) . tap ( block ) . render else @footer = UiBibz :: Ui :: Ux :: Containers :: Components :: PanelFooter . new ( content , options , html_options , block ) . render end end


Input: header use i18n [CODESPLIT] def header column , name = nil @column = column defaults = [ translate_headers_by_defaults , translate_headers_by_defaults_active_record , translate_headers_by_active_record , header_name ( name ) ] @name = UiBibz :: Utils :: Internationalization . new ( translate_headers_by_model , default : defaults ) . translate sortable? ? sortable_link : title end


Input: See UiBibz :: Ui :: Core :: Boxes :: Card . initialize Render html tag [CODESPLIT] def pre_render init_components content_tag :div , html_options do form_tag ( url_for ( url_parameters ) , method : :get ) do store . parameters . with_indifferent_access . reject { | k , v | default_parameters? ( k ) || v . blank? } . each do | k , v | concat tag ( :input , type : 'hidden' , name : k , value : v ) end concat tag ( :input , type : 'hidden' , name : 'store_id' , value : store . id ) unless store . id . nil? # if there is more one table in html page concat @items . join . html_safe end end end


Input: Add column in table [CODESPLIT] def column data_index = nil , options = nil , html_options = nil , & block @columns << Column . new ( data_index , options , html_options , block ) end


Input: Add link action in table [CODESPLIT] def link content = nil , options = nil , html_options = nil , & block @actions << UiBibz :: Ui :: Core :: Forms :: Dropdowns :: Components :: DropdownLink . new ( content , options , html_options , block ) . render end


Input: Create an Rails plugin engine for documentation site [CODESPLIT] def engine_scaffold FileUtils . mkdir_p ( @gem_temp ) Dir . chdir ( @gem_temp ) do response = Open3 . capture3 ( "rails plugin new #{gem} --mountable --dummy-path=site --skip-test-unit" ) if ! response [ 1 ] . empty? puts response [ 1 ] abort "FAILED: Please be sure you have the rails gem installed with `gem install rails`" end # Remove files and directories that are unnecessary for the # light-weight Rails documentation site remove = %w( mailers models assets channels jobs views ) . map { | f | File . join ( 'app' , f ) } remove . concat %w( cable.yml storage.yml database.yml ) . map { | f | File . join ( 'config' , f ) } remove . each { | f | FileUtils . rm_rf File . join ( @gem , 'site' , f ) , secure : true } end engine_copy end


Input: Copy parts of the engine scaffold into site directory [CODESPLIT] def engine_copy site_path = File . join path , 'site' FileUtils . mkdir_p site_path ## Copy Rails plugin files Dir . chdir "#{@gem_temp}/#{gem}/site" do %w( app config bin config.ru Rakefile public log ) . each do | item | target = File . join site_path , item FileUtils . cp_r item , target action_log "create" , target . sub ( @cwd + '/' , '' ) end end # Remove temp dir FileUtils . rm_rf @gem_temp end


Input: reports [CODESPLIT] def z_report_session device . session ( "Z Report" ) do | s | s . notify "Z Report Start" s . fsend Closure :: DAY_FIN_REPORT , "0" s . notify "Z Report End" end end


Input: If underscore keys copy children to top level vars too Input : _colors : yellow : #fco Output : colors : { yellow : #fco } yellow : #fco [CODESPLIT] def promote_keys ( data ) data . keys . select { | k | k . start_with? ( '_' ) } . each do | key | data [ key . sub ( / / , '' ) ] = data [ key ] data = data . delete ( key ) . merge ( data ) end data end


Input: Convert [CODESPLIT] def convert_to_sass_value ( item ) if item . is_a? Array make_list ( item ) elsif item . is_a? Hash make_map ( item ) else item . to_s end end


Input: Convert hashes to Sass map syntax [CODESPLIT] def make_map ( item ) '(' + item . map { | key , value | key . to_s + ':' + convert_to_sass_value ( value ) } . join ( ',' ) + ')' end


Input: basket [CODESPLIT] def sale_and_pay_items_session ( items = [ ] , operator = "1" , password = "1" ) device . session ( "Fiscal Doc" ) do | s | s . notify "Fiscal Doc Start" s . open_fiscal_doc s . notify "Register Sale" items . each do | item | s . add_sale ( item ) end s . notify "Register Payment" s . total_payment s . notify "Close Fiscal Receipt" s . close_fiscal_doc s . notify "Fiscal Doc End" end end


Input: alias_method : print : push [CODESPLIT] def print ( text ) if device . encoding . present? push text . encode ( device . encoding ) else push text end end


Input: reports [CODESPLIT] def z_report_session device . session ( "Z Report" ) do | s | s . notify "Z Report Start" s . fsend Reports :: DAILY_REPORT , FLAG_TRUE status = s . get_printer_status s . notify "Z Report End" end end


Input: def build_sale_data ( price text1 = text2 = nil tax_group = 2 qty = 1 percent = nil neto = nil number = nil ) [CODESPLIT] def build_sale_data ( sale_item ) "" . b . tap ( ) do | data | price_units = ( sale_item . price * 100 ) . to_i # !FIXME price_bytes = "" . b 4 . times { | shift | price_bytes . insert 0 , ( ( price_units >> shift 8 ) & 0xff ) . chr } data << price_bytes qty_units = ( ( sale_item . qty || 1 ) * 1000 ) . to_i # !FIXME qty_bytes = "" . b 4 . times { | shift | qty_bytes . insert 0 , ( ( qty_units >> shift 8 ) & 0xff ) . chr } data << qty_bytes data << "\x00" . b #number len FIXME data << "\xAA\xAA\xAA\xAA\xAA\xAA" . b #number FIXME text = sale_item . text1 . truncate ( 20 ) data << text . length . chr data << text . ljust ( 20 , " " ) . b data << ( sale_item . tax_group || 2 ) . chr end end


Input: POST / devices [CODESPLIT] def create @device = extfaceable . extface_devices . new ( device_params ) if @device . save redirect_to @device , notice : 'Device was successfully created.' else render action : :form end end


Input: Create a new Rails :: Engine [CODESPLIT] def create_engine ( & block ) @engine = parent_module . const_set ( 'Engine' , Class . new ( Rails :: Engine ) do def spark_plugin_path parent = Object . const_get ( self . class . name . sub ( / / , '' ) ) Pathname . new parent . instance_variable_get ( "@gem_path" ) end def config @config ||= Rails :: Engine :: Configuration . new ( spark_plugin_path ) end engine_name SparkEngine . plugin . name require 'spark_engine/middleware' # Ensure compiled assets in /public are served initializer "#{name}.static_assets" do | app | if app . config . public_file_server . enabled app . middleware . insert_after :: ActionDispatch :: Static , SparkEngine :: StaticAssets , "#{root}/public" , engine_name : SparkEngine . plugin . name app . middleware . insert_before :: ActionDispatch :: Static , Rack :: Deflater end end initializer "#{name}.view_paths" do | app | # Ensure Components are readable from engine paths ActiveSupport . on_load :action_controller do append_view_path "#{SparkEngine.plugin.paths[:components]}" end end initializer "#{name}.asset_paths" do | app | app . config . assets . paths << SparkEngine . plugin . paths [ :components ] end end ) # Autoload engine lib and components path @engine . config . autoload_paths . concat [ File . join ( @engine . spark_plugin_path , "lib" ) , SparkEngine . plugin . paths [ :components ] ] @engine . config . after_initialize do | app | if defined? ( SassC ) && defined? ( SassC :: Rails ) # Inject Sass importer for yaml files require "spark_engine/sassc/importer" SassC :: Rails :: Importer :: EXTENSIONS << SassC :: SparkEngine :: Importer :: SassYamlExtension . new elsif defined? ( Sass ) # Overwrite Sass engine with Yaml support require "spark_engine/sass/engine" end end # Takes a block passed an evaluates it in the context of a Rails engine # This allows plugins to modify engines when created. @engine . instance_eval ( block ) if block_given? end


Input: Find files based on class type and return an array of Classes for each file [CODESPLIT] def add_files ( klass ) ext = asset_ext klass find_files ( ext ) . map do | path | klass . new ( self , path ) end end


Input: Find files by class type and extension [CODESPLIT] def find_files ( ext ) files = Dir [ File . join ( paths [ ext . to_sym ] , asset_glob ( ext ) ) ] # Filter out partials files . reject { | f | File . basename ( f ) . start_with? ( '_' ) } end


Input: Convert configuration into instance variables [CODESPLIT] def set_instance ( name , value ) instance_variable_set ( "@#{name}" , value ) instance_eval ( <<-EOS , __FILE__ , __LINE__ + 1 ) #{ name } #{ name } EOS end


Input: Handles running threaded commands [CODESPLIT] def dispatch ( command , * args ) @threads = [ ] send command , args @threads . each { | thr | thr . join } end


Input: Build assets [CODESPLIT] def build ( options = { } ) puts SparkEngine . production? ? 'Building for production…' : ' uilding…' require_rails clean if SparkEngine . production? SparkEngine . plugin . build ( options ) end


Input: Watch assets for changes and build [CODESPLIT] def watch ( options = { } ) build ( options ) require 'listen' trap ( "SIGINT" ) { puts "\nspark_engine watcher stopped. Have a nice day!" exit! } @threads . concat SparkEngine . load_plugin . watch ( options ) end


Input: todo / fix : pass in known_grounds as a parameter? why? why not? todo / fix : remove = nil in para - make param required w / o fallback [CODESPLIT] def map_ground! ( line , known_grounds = nil ) if known_grounds . nil? puts "depreciated API call map_ground! (pass in mapping table as 2nd param)" known_grounds = @known_grounds end TextUtils . map_titles_for! ( 'ground' , line , known_grounds ) end


Input: todo / fix : remove = nil in para - make param required w / o fallback [CODESPLIT] def map_person! ( line , known_persons = nil ) if known_persons . nil? puts "depreciated API call map_person! (pass in mapping table as 2nd param)" known_persons = @known_persons end TextUtils . map_titles_for! ( 'person' , line , known_persons ) end


Input: method find_rsssf_scores! [CODESPLIT] def find_rsssf_date! ( line , opts = { } ) finder = RsssfDateFinder . new finder . find! ( line , opts ) end


Input:
method find_rsssf_round! [CODESPLIT] def parse_round_header ( line ) ## todo/fix:
 ##   simplify - for now round number always required
 #      e.g. no auto-calculation supported here
 #       fail if round found w/o number/pos !!!
 #
 #  also remove knockout flag for now (set to always false for now)
 logger . debug "parsing round header line: >#{line}<" ## check for date in header first e.g. Round 36 [Jul 20]  !!
 ##   avoid "conflict" with getting "wrong" round number from date etc.
 date = find_rsssf_date! ( line , start_at : @event . start_at ) if date @last_date = date end title , pos = find_rsssf_round! ( line ) ## check if pos available; if not auto-number/calculate
 if pos . nil? logger . error ( "  no round pos found in line >#{line}<; round pos required in rsssf; sorry" ) fail ( "round pos required in rsssf; sorry" ) end logger . debug "  line: >#{line}<" ## Note: dummy/placeholder start_at, end_at date
 ##  replace/patch after adding all games for round
 round_attribs = { title : title , title2 : nil , knockout : false } round = Round . find_by ( event_id : @event . id , pos : pos ) if round . present? logger . debug "update round #{round.id}:" else logger . debug "create round:" round = Round . new round_attribs = round_attribs . merge ( { event_id : @event . id , pos : pos , ##  todo: add num e.g. num == pos for round 1, round 2, etc. - why? why not??
 start_at : Date . parse ( '1911-11-11' ) , end_at : Date . parse ( '1911-11-11' ) } ) end logger . debug round_attribs . to_json round . update_attributes! ( round_attribs ) ### store list of round ids for patching start_at/end_at at the end
 @patch_round_ids << round . id @last_round = round ## keep track of last seen round for matches that follow etc.
 end


Input: todo : allow all - in - one literal form a la kicker e . g . 2 : 2 ( 1 : 1 1 : 0 ) n . V . 5 : 1 i . E . [CODESPLIT] def find! ( line , opts = { } ) ### fix: add and match all-in-one literal first, followed by # note: always call after find_dates !!! #  scores match date-like patterns!!  e.g. 10-11  or 10:00 etc. #   -- note: score might have two digits too ### fix: depending on language allow 1:1 or 1-1 ##   do NOT allow mix and match ##  e.g. default to en is  1-1 ##    de is 1:1 etc. # extract score from line # and return it # note: side effect - removes date from line string score1i = nil # half time (ht) scores score2i = nil score1 = nil # full time (ft) scores score2 = nil score1et = nil # extra time (et) scores score2et = nil score1p = nil # penalty (p) scores score2p = nil if ( md = EN__P_ET_FT_HT__REGEX . match ( line ) ) score1i = md [ :score1i ] . to_i score2i = md [ :score2i ] . to_i score1 = md [ :score1 ] . to_i score2 = md [ :score2 ] . to_i score1et = md [ :score1et ] . to_i score2et = md [ :score2et ] . to_i score1p = md [ :score1p ] . to_i score2p = md [ :score2p ] . to_i logger . debug "   score.en__p_et_ft_ht: >#{score1p}-#{score2p} pen. #{score1et}-#{score2et} a.e.t. (#{score1}-#{score2}, #{score1i}-#{score2i})<" line . sub! ( md [ 0 ] , '[SCORES.EN__P_ET_FT_HT]' ) elsif ( md = EN__ET_FT_HT__REGEX . match ( line ) ) score1i = md [ :score1i ] . to_i score2i = md [ :score2i ] . to_i score1 = md [ :score1 ] . to_i score2 = md [ :score2 ] . to_i score1et = md [ :score1et ] . to_i score2et = md [ :score2et ] . to_i logger . debug "   score.en__et_ft_ht: >#{score1et}-#{score2et} a.e.t. (#{score1}-#{score2}, #{score1i}-#{score2i})<" line . sub! ( md [ 0 ] , '[SCORES.EN__ET_FT_HT]' ) elsif ( md = EN__FT_HT__REGEX . match ( line ) ) score1i = md [ :score1i ] . to_i score2i = md [ :score2i ] . to_i score1 = md [ :score1 ] . to_i score2 = md [ :score2 ] . to_i logger . debug "   score.en__ft_ht: >#{score1}-#{score2} (#{score1i}-#{score2i})<" line . sub! ( md [ 0 ] , '[SCORES.EN__FT_HT]' ) else ####################################################### ## try "standard" generic patterns for fallbacks if ( md = ET_REGEX . match ( line ) ) score1et = md [ :score1 ] . to_i score2et = md [ :score2 ] . to_i logger . debug "   score.et: >#{score1et}-#{score2et}<" line . sub! ( md [ 0 ] , '[SCORE.ET]' ) end if ( md = P_REGEX . match ( line ) ) score1p = md [ :score1 ] . to_i score2p = md [ :score2 ] . to_i logger . debug "   score.p: >#{score1p}-#{score2p}<" line . sub! ( md [ 0 ] , '[SCORE.P]' ) end ## let full time (ft) standard regex go last - has no marker if ( md = FT_REGEX . match ( line ) ) score1 = md [ :score1 ] . to_i score2 = md [ :score2 ] . to_i logger . debug "   score: >#{score1}-#{score2}<" line . sub! ( md [ 0 ] , '[SCORE]' ) end end ## todo: how to handle game w/o extra time #   but w/ optional penalty ???  e.g. used in copa liberatores, for example #    retrun 0,0 or nil,nil for extra time score ?? or -1, -1 ?? #    for now use nil,nil scores = [ ] scores += [ score1i , score2i ] if score1p || score2p || score1et || score2et || score1 || score2 || score1i || score2i scores += [ score1 , score2 ] if score1p || score2p || score1et || score2et || score1 || score2 scores += [ score1et , score2et ] if score1p || score2p || score1et || score2et scores += [ score1p , score2p ] if score1p || score2p scores end


Input:
method load_fixtures [CODESPLIT] def handle_round ( round_pos_str ) round_pos = round_pos_str . to_i round_attribs = { } round = Round . find_by ( event_id : @event . id , pos : round_pos ) if round . present? logger . debug "update round #{round.id}:" else logger . debug "create round:" round = Round . new round_attribs = round_attribs . merge ( { event_id : @event . id , pos : round_pos , title : "Round #{round_pos}" , title2 : nil , knockout : false , start_at : Date . parse ( '1911-11-11' ) , end_at : Date . parse ( '1911-11-11' ) } ) end logger . debug round_attribs . to_json round . update_attributes! ( round_attribs ) ### store list of round ids for patching start_at/end_at at the end
 @patch_round_ids << round . id @last_round = round ## keep track of last seen round for matches that follow etc.
 end


Input:
method handle_game [CODESPLIT] def parse_fixtures CSV . parse ( @text , headers : true ) do | row | puts row . inspect pp round = row [ 'Round' ] pp date = row [ 'Date' ] pp team1 = row [ 'Team 1' ] pp team2 = row [ 'Team 2' ] pp ft = row [ 'FT' ] pp ht = row [ 'HT' ] ## find round by pos
 if round handle_round ( round ) handle_game ( date , team1 , team2 , ft , ht ) else fail "round required for import; sorry" end end ###########################
 # backtrack and patch round dates (start_at/end_at)
 unless @patch_round_ids . empty? ###
 # note: use uniq - to allow multiple round headers (possible?)
 Round . find ( @patch_round_ids . uniq ) . each do | r | logger . debug "patch round start_at/end_at date for #{r.title}:" ## note:
 ## will add "scope" pos first e.g
 #
 ## SELECT "games".* FROM "games"  WHERE "games"."round_id" = ?
 # ORDER BY pos, play_at asc  [["round_id", 7]]
 #   thus will NOT order by play_at but by pos first!!!
 # =>
 #  need to unscope pos!!! or use unordered_games - games_by_play_at_date etc.??
 #   thus use reorder()!!! - not just order('play_at asc')
 games = r . games . reorder ( 'play_at asc' ) . all ## skip rounds w/ no games
 ## todo/check/fix: what's the best way for checking assoc w/ 0 recs?
 next if games . size == 0 # note: make sure start_at/end_at is date only (e.g. use play_at.to_date)
 #   sqlite3 saves datetime in date field as datetime, for example (will break date compares later!)
 round_attribs = { start_at : games [ 0 ] . play_at . to_date , # use games.first ?
 end_at : games [ - 1 ] . play_at . to_date # use games.last ? why? why not?
 } logger . debug round_attribs . to_json r . update_attributes! ( round_attribs ) end end end


Input: method run [CODESPLIT] def load_fixtures_with_include_path ( name , include_path ) # load from file system path = "#{include_path}/#{name}.rb" puts "*** loading data '#{name}' (#{path})..." ## nb: assume/enfore utf-8 encoding (with or without BOM - byte order mark) ## - see sportdb/utils.rb code = File . read_utf8 ( path ) load_fixtures_worker ( code ) Prop . create! ( key : "db.#{fixture_name_to_prop_key(name)}.version" , value : "file.rb.#{File.mtime(path).strftime('%Y.%m.%d')}" ) end


Input:
fix / todo : check that [ ROUND . TITLE2 ] and friends do NOT use pipes ( | ) change all pipes ( | ) to dot ( . ) - pipes get used for def markers!!! [CODESPLIT] def find_round_header_title2! ( line ) ## todo/fix:
 ##  cleanup method
 ##   use  buf.index( '//' ) to split string (see found_round_def)
 ##     why? simpler why not?
 ##  - do we currently allow groups if title2 present? add example if it works?
 # assume everything after // is title2 - strip off leading n trailing whitespaces
 regex = / \/ \s \s / if line =~ regex logger . debug "   title2: >#{$1}<" line . sub! ( regex , '[ROUND.TITLE2]' ) return $1 else return nil # no round title2 found (title2 is optional)
 end end


Input: method load_fixtures [CODESPLIT] def parse_group_header ( line ) logger . debug "parsing group header line: >#{line}<" # note: group header resets (last) round  (allows, for example): #  e.g. #  Group Playoffs/Replays       -- round header #    team1 team2                -- match #  Group B:                     -- group header #    team1 team2 - match  (will get new auto-matchday! not last round) @round = nil ## fix: change/rename to @last_round !!! title , pos = find_group_title_and_pos! ( line ) logger . debug "    title: >#{title}<" logger . debug "    pos: >#{pos}<" logger . debug "  line: >#{line}<" # set group for games @group = Group . find_by_event_id_and_pos! ( @event . id , pos ) end


Input: method parse_goals = begin ###### add to person and use!!! def self . create_or_update_from_values ( values more_attribs = {} ) ## key & title required [CODESPLIT] def parse_fixtures ( reader ) reader . each_line do | line | if is_goals? ( line ) parse_goals ( line ) elsif is_round_def? ( line ) ## todo/fix:  add round definition (w begin n end date) ## todo: do not patch rounds with definition (already assume begin/end date is good) ##  -- how to deal with matches that get rescheduled/postponed? parse_round_def ( line ) elsif is_round? ( line ) parse_round_header ( line ) elsif is_group_def? ( line ) ## NB: group goes after round (round may contain group marker too) ### todo: add pipe (|) marker (required) parse_group_def ( line ) elsif is_group? ( line ) ##  -- lets you set group  e.g. Group A etc. parse_group_header ( line ) elsif try_parse_game ( line ) # do nothing here elsif try_parse_date_header ( line ) # do nothing here else logger . info "skipping line (no match found): >#{line}<" end end # lines.each ########################### # backtrack and patch round pos and round dates (start_at/end_at) #  note: patch dates must go first! (otherwise sort_by_date will not work for round pos) unless @patch_round_ids_dates . empty? ### #  fix: do NOT patch if auto flag is set to false !!! #   e.g. rounds got added w/ round def (not w/ round header) # note: use uniq - to allow multiple round headers (possible?) Round . find ( @patch_round_ids_dates . uniq ) . each do | r | logger . debug "patch round start_at/end_at date for #{r.title}:" ## note: ## will add "scope" pos first e.g # ## SELECT "games".* FROM "games"  WHERE "games"."round_id" = ? # ORDER BY pos, play_at asc  [["round_id", 7]] #   thus will NOT order by play_at but by pos first!!! # => #  need to unscope pos!!! or use unordered_games - games_by_play_at_date etc.?? #   thus use reorder()!!! - not just order('play_at asc') games = r . games . reorder ( 'play_at asc' ) . all ## skip rounds w/ no games ## todo/check/fix: what's the best way for checking assoc w/ 0 recs? next if games . size == 0 # note: make sure start_at/end_at is date only (e.g. use play_at.to_date) #   sqlite3 saves datetime in date field as datetime, for example (will break date compares later!) round_attribs = { start_at : games [ 0 ] . play_at . to_date , # use games.first ? end_at : games [ - 1 ] . play_at . to_date # use games.last ? why? why not? } logger . debug round_attribs . to_json r . update_attributes! ( round_attribs ) end end unless @patch_round_ids_pos . empty? # step 0: check for offset (last_round_pos) if @last_round_pos offset = @last_round_pos logger . info "  +++ patch round pos - use offset; start w/ #{offset}" else offset = 0 logger . debug "  patch round pos - no offset; start w/ 0" end # step 1: sort by date # step 2: update pos # note: use uniq - to allow multiple round headers (possible?) Round . order ( 'start_at asc' ) . find ( @patch_round_ids_pos . uniq ) . each_with_index do | r , idx | # note: starts counting w/ zero(0) logger . debug "[#{idx+1}] patch round pos >#{offset+idx+1}< for #{r.title}:" round_attribs = { pos : offset + idx + 1 } # update title if Matchday XXXX  e.g. use Matchday 1 etc. if r . title . starts_with? ( 'Matchday' ) round_attribs [ :title ] = "Matchday #{offset+idx+1}" end logger . debug round_attribs . to_json r . update_attributes! ( round_attribs ) # update last_round_pos offset too @last_round_pos = [ offset + idx + 1 , @last_round_pos || 0 ] . max end end end


Input:
e . g . cut_off_end_of_line_comment! [CODESPLIT] def find! ( line , opts = { } ) # remove end-of-line comments
 #   - move to textutils ?? why? why not??
 cut_off_end_of_line_comment! ( line ) ## note: func defined in utils.rb (FixtureHelpers)
 # remove [] if presents e.g. [Neymar 12']
 line = line . gsub ( / \[ \] / , '' ) # remove (single match) if line starts w/ - (allow spaces)  e.g. [-;Neymar 12'] or [ - ;Neymar 12']
 line = line . sub ( / / , '' ) # split into left hand side (lhs) for team1 and
 #            right hand side (rhs) for team2
 values = line . split ( ';' ) # note: allow empty right hand side (e.g. team2 did NOT score any goals e.g. 3-0 etc.)
 lhs = values [ 0 ] rhs = values [ 1 ] lhs = lhs . strip unless lhs . nil? rhs = rhs . strip unless rhs . nil? parser = GoalsParser . new ## todo/check: only call if not nil?
 logger . debug "  lhs (team1): >#{lhs}<" lhs_data = parser . parse! ( lhs ) pp lhs_data logger . debug "  rhs (team2): >#{rhs}<" rhs_data = parser . parse! ( rhs ) pp rhs_data ### merge into flat goal structs
 goals = [ ] lhs_data . each do | player | player . minutes . each do | minute | goal = GoalStruct . new goal . name = player . name goal . team = 1 goal . minute = minute . minute goal . offset = minute . offset goal . penalty = minute . penalty goal . owngoal = minute . owngoal goals << goal end end rhs_data . each do | player | player . minutes . each do | minute | goal = GoalStruct . new goal . name = player . name goal . team = 2 goal . minute = minute . minute goal . offset = minute . offset goal . penalty = minute . penalty goal . owngoal = minute . owngoal goals << goal end end # sort by minute + offset
 goals = goals . sort do | l , r | res = l . minute <=> r . minute if res == 0 res = l . offset <=> r . offset # pass 2: sort by offset
 end res end ## calc score1,score2
 score1 = 0 score2 = 0 goals . each do | goal | if goal . team == 1 score1 += 1 elsif goal . team == 2 score2 += 1 else # todo: should not happen: issue warning
 end goal . score1 = score1 goal . score2 = score2 end logger . debug "  #{goals.size} goals:" pp goals goals end


Input: method find_files [CODESPLIT] def patch ( save = false ) files = find_files change_logs = [ ] files . each do | file | p = PrettyPrinter . from_file ( file ) new_text , change_log = p . patch next if change_log . empty? ## no changes if save File . open ( file , 'w' ) do | f | f . write new_text end end change_logs << [ file , change_log ] end change_logs ## return change_logs or empty array end


Input: lets us use match_teams_for_country etc . [CODESPLIT] def load_setup ( name ) reader = create_fixture_reader ( name ) reader . each do | fixture_name | load ( fixture_name ) end end


Input:
method load_setup [CODESPLIT] def load ( name ) # convenience helper for all-in-one reader
 logger . debug "enter load( name=>>#{name}<<)" ## formerly also printed -> include_path=>>#{include_path}<<
 if match_players_for_country ( name ) do | country_key | ## country = Country.find_by_key!( country_key )
 ## fix-fix-fix-fix-fix-fix: change to new format e.g. from_file, from_zip etc!!!
 ## reader = PersonDb::PersonReader.new( include_path )
 ## reader.read( name, country_id: country.id )
 end elsif name =~ / \/ \/ / # e.g. ajax.txt bayern.txt etc.
 ## note: for now assume club (e.g. no dash (-) allowed for country code e.g. br-brazil etc.)
 team = Team . find_by_key! ( $1 ) ## note: pass in @event.id - that is, last seen event (e.g. parsed via GameReader/MatchReader)
 reader = create_club_squad_reader ( name , team_id : team . id , event_id : @event . id ) reader . read ( ) elsif name =~ / \/ \/ \/ / ## fix: add to country matcher new format
 ##   name is country! and parent folder is type name e.g. /squads/br-brazil
 # note: if two letters, assume country key
 #       if three letters, assume team key
 ##   allow three letter codes
 ##  assume three letter code are *team* codes (e.g. fdr, gdr, etc)
 ##      not country code (allows multiple teams per country)
 if $1 . length == 2 ## get national team via country
 country = Country . find_by_key! ( $1 ) ###  for now assume country code matches team for now (do NOT forget to downcase e.g. BRA==bra)
 logger . info "  assume country code == team code for #{country.code}" team = Team . find_by_key! ( country . code . downcase ) else # assume length == 3
 ## get national team directly (use three letter fifa code)
 team = Team . find_by_key! ( $1 ) end ## note: pass in @event.id - that is, last seen event (e.g. parsed via GameReader/MatchReader)
 reader = create_national_team_squad_reader ( name , team_id : team . id , event_id : @event . id ) reader . read ( ) elsif name =~ / \/ / # NB: ^seasons or also possible at-austria!/seasons
 reader = create_season_reader ( name ) reader . read ( ) elsif name =~ / \/ / # NB: ^assocs or also possible national-teams!/assocs
 reader = create_assoc_reader ( name ) reader . read ( ) elsif match_stadiums_for_country ( name ) do | country_key | country = Country . find_by_key! ( country_key ) reader = create_ground_reader ( name , country_id : country . id ) reader . read ( ) end elsif match_leagues_for_country ( name ) do | country_key | # name =~ /^([a-z]{2})\/leagues/
 # auto-add country code (from folder structure) for country-specific leagues
 #  e.g. at/leagues
 country = Country . find_by_key! ( country_key ) reader = create_league_reader ( name , club : true , country_id : country . id ) reader . read ( ) end elsif name =~ / \/ / # NB: ^leagues or also possible world!/leagues  - NB: make sure goes after leagues_for_country!!
 reader = create_league_reader ( name ) reader . read ( ) elsif match_teams_for_country ( name ) do | country_key | # name =~ /^([a-z]{2})\/teams/
 # auto-add country code (from folder structure) for country-specific teams
 #  e.g. at/teams at/teams.2 de/teams etc.
 country = Country . find_by_key! ( country_key ) reader = create_team_reader ( name , country_id : country . id ) reader . read ( ) end elsif match_clubs_for_country ( name ) do | country_key | # name =~ /^([a-z]{2})\/clubs/
 # auto-add country code (from folder structure) for country-specific clubs
 #  e.g. at/teams at/teams.2 de/teams etc.
 country = Country . find_by_key! ( country_key ) reader = create_team_reader ( name , club : true , country_id : country . id ) ## note: always sets club flag to true
 reader . read ( ) end elsif name =~ / \/ / ## fix: check if teams rule above (e.g. /^teams/ )conflicts/matches first ???
 ### fix: use new NationalTeamReader ??? why? why not?
 reader = create_team_reader ( name ) ## note: always sets club flag to true / national to true
 reader . read ( ) elsif name =~ / \/ / ### fix: use new ClubReader ??? why? why not?
 reader = create_team_reader ( name , club : true ) ## note: always sets club flag to true / national to false
 reader . read ( ) elsif name =~ / \. / ## e.g.  1-premierleague.conf  => 1-premierleague.conf.txt
 reader = create_event_table_reader ( name ) reader . read ( ) # note: keep a "public" reference of last event in @event  - e.g. used/required by squads etc.
 @event = reader . event elsif name =~ / \/ \d \d \- \d \/ \/ / || name =~ / \/ \d \d \- \d / # note: allow 2013_14 or 2013-14 (that, is dash or underscore)
 # e.g. must match /2012/ or /2012_13/  or   /2012--xxx/ or /2012_13--xx/
 #  or   /2012 or /2012_13   e.g. brazil/2012 or brazil/2012_13
 reader = create_game_reader ( name ) reader . read ( ) # note: keep a "public" reference of last event in @event  - e.g. used/required by squads etc.
 @event = reader . event else logger . error "unknown sportdb fixture type >#{name}<" # todo/fix: exit w/ error
 end end


Input: replace_images newer versions of LibreOffice can t open files with duplicates image names [CODESPLIT] def avoid_duplicate_image_names ( content ) nodes = content . xpath ( "//draw:frame[@draw:name]" ) nodes . each_with_index do | node , i | node . attribute ( 'name' ) . value = "pic_#{i}" end end


Input: Get the hash of the key and value specified for the scope . [CODESPLIT] def scope_params return { } if dynamic_scaffold . scope . nil? case dynamic_scaffold . scope when Array then dynamic_scaffold . scope . each_with_object ( { } ) do | val , res | if val . is_a? Hash val . each { | k , v | res [ k ] = v } else res [ val ] = params [ val ] end end when Hash then dynamic_scaffold . scope end end


Input: Convert pkey_string value to hash . [CODESPLIT] def pkey_string_to_hash ( pkey ) # https://github.com/gomo/dynamic_scaffold/pull/9/commits/ff5de0e38b3544347e82539c45ffd2efaf3410da # Stop support multiple pkey, on this commit. # Convert "key:1,code:foo" to {key: "1", code: "foo"} pkey . split ( ',' ) . map { | v | v . split ( ':' ) } . each_with_object ( { } ) { | v , res | res [ v . first ] = v . last } end


Input: Get paramters for sort action . pkeys [] [ column ] = > value [CODESPLIT] def sort_params params . require ( 'pkeys' ) . map { | p | p . permit ( dynamic_scaffold . model . primary_key ) } end


Input: Get paramters for update record . [CODESPLIT] def update_values # rubocop:disable Metrics/AbcSize # set the parameters of carrierwave_image at the end for validates. permitting = [ ] dynamic_scaffold . form . items . reject { | i | i . type? ( :carrierwave_image ) } . each do | item | item . extract_parameters ( permitting ) end permitting . concat ( dynamic_scaffold . form . permit_params ) dynamic_scaffold . form . items . select { | i | i . type? ( :carrierwave_image ) } . each do | item | item . extract_parameters ( permitting ) end values = params . require ( dynamic_scaffold . model . name . underscore ) . permit ( permitting ) if dynamic_scaffold . scope && ! valid_for_scope? ( values ) raise DynamicScaffold :: Error :: InvalidOperation , "You can update only to #{scope_params} on this scope" end values end


Input: Check if there are inconsistent scopes in update parameters [CODESPLIT] def valid_for_scope? ( update_params ) return true if dynamic_scaffold . scope_options [ :changeable ] result = true scope_params . each do | key , value | if update_params . key? ( key ) && update_params [ key ] != value result = false break end end result end


Input: Actions [CODESPLIT] def index # rubocop:disable Metrics/AbcSize @records = dynamic_scaffold . list . build_sql ( scope_params ) @count = @records . count unless dynamic_scaffold . max_count . nil? @records = handle_pagination ( @records ) @records = @records . order dynamic_scaffold . list . sorter if dynamic_scaffold . list . sorter @records = @records . order ( dynamic_scaffold . list . order ) unless dynamic_scaffold . list . order . empty? ret = yield ( @records ) if block_given? @records = ret unless ret . nil? unless @records . is_a? :: ActiveRecord :: Relation raise ( Error :: InvalidOperation , 'You must return ActiveRecord::Relation from super block' ) end @records end


Input: number tokens are added to the bucket every period seconds ( up to a max of number tokens being available ) . Each time a resource is used a token is removed from the bucket ; if no tokens are available no resource may be used . [CODESPLIT] def take took = @redis . with do | conn | RedisLocks . evalsha_or_eval ( conn : conn , script : SCRIPT , digest : DIGEST , keys : [ @key ] , args : [ epoch_f ( conn ) , @rps , @burst ] ) end took == 1 end


Input: Acquire a resource from the semaphore if available . Returns false if no resources are available . [CODESPLIT] def lock ( timeout : nil , & block ) ensure_exists_and_release_stale_locks! success = @redis . with do | conn | if timeout ! conn . blpop ( available_key , timeout . to_i ) . nil? else ! conn . lpop ( available_key ) . nil? end end return false unless success token = SecureRandom . hex ( 16 ) @tokens . push ( token ) @redis . with do | conn | conn . zadd ( grabbed_key , epoch_f ( conn ) , token ) end return_or_yield ( token , block ) end


Input: Release a resource back to the semaphore . Should normally be called with an explicit token . [CODESPLIT] def unlock ( token = @tokens . pop ) return unless token removed = false @redis . with do | conn | removed = conn . zrem grabbed_key , token if removed conn . lpush available_key , 1 end end removed end


Input: Creates a notification object . [CODESPLIT] def apply_options ( options = { } ) options . each { | key , value | send ( "#{key}=" , value ) if respond_to? ( key ) } yield ( self ) if block_given? end


Input: Shows a new notification . [CODESPLIT] def show! notify_init ( app_name ) or raise "notify_init failed" raw_ptr = notify_notification_new ( summary , body , icon_path , nil ) @notification = :: FFI :: AutoPointer . new ( raw_ptr , method ( :g_object_unref ) ) show end


Input: Updates a previously shown notification or creates a new one . [CODESPLIT] def update ( options = { } , & block ) apply_options ( options , block ) if @notification notify_notification_update ( @notification , summary , body , icon_path , nil ) show else show! end end


Input: Returns a usable youtube - dl executable ( system or vendor ) [CODESPLIT] def usable_executable_path_for ( exe ) system_path = which ( exe ) if system_path . nil? # TODO: Search vendor bin for executable before just saying it's there. vendor_path = File . absolute_path ( "#{__FILE__}/../../../vendor/bin/#{exe}" ) File . chmod ( 775 , vendor_path ) unless File . executable? ( vendor_path ) # Make sure vendor binary is executable vendor_path else system_path . strip end end


Input: Helper for doing lines of cocaine ( initializing auto executable stuff etc ) [CODESPLIT] def cocaine_line ( command , executable_path = nil ) executable_path = executable_path_for ( 'youtube-dl' ) if executable_path . nil? Cocaine :: CommandLine . new ( executable_path , command ) end


Input: Instantiate new model [CODESPLIT] def download raise ArgumentError . new ( 'url cannot be nil' ) if @url . nil? raise ArgumentError . new ( 'url cannot be empty' ) if @url . empty? set_information_from_json ( YoutubeDL :: Runner . new ( url , runner_options ) . run ) end


Input: Redirect methods for information getting [CODESPLIT] def method_missing ( method , * args , & block ) value = information [ method ] if value . nil? super else value end end


Input: Parses options and converts them to Cocaine s syntax [CODESPLIT] def options_to_commands commands = [ ] @options . sanitize_keys . each_paramized_key do | key , paramized_key | if @options [ key ] . to_s == 'true' commands . push "--#{paramized_key}" elsif @options [ key ] . to_s == 'false' commands . push "--no-#{paramized_key}" else commands . push "--#{paramized_key} :#{key}" end end commands . push quoted ( url ) commands . join ( ' ' ) end


Input: Merge options with given hash removing banned keys and returning a new instance of Options . [CODESPLIT] def with ( hash ) merged = Options . new ( @store . merge ( hash . to_h ) ) merged . banned_keys = @banned_keys merged . send ( :remove_banned ) merged end


Input: Option getting and setting using ghost methods [CODESPLIT] def method_missing ( method , * args , & _block ) remove_banned if method . to_s . include? '=' method = method . to_s . tr ( '=' , '' ) . to_sym return nil if banned? method @store [ method ] = args . first else return nil if banned? method @store [ method ] end end


Input: Calls a block to do operations on keys See sanitize_keys! for examples [CODESPLIT] def manipulate_keys! ( & block ) @store . keys . each do | old_name | new_name = block . call ( old_name ) unless new_name == old_name @store [ new_name ] = @store [ old_name ] @store . delete ( old_name ) end end end


Input: Symbolizes and sanitizes keys in the option store [CODESPLIT] def sanitize_keys! # Symbolize manipulate_keys! { | key_name | key_name . is_a? ( Symbol ) ? key_name : key_name . to_sym } # Underscoreize (because Cocaine doesn't like hyphens) manipulate_keys! { | key_name | key_name . to_s . tr ( '-' , '_' ) . to_sym } end


Input: Allowable options are : - : environment e . g . test - : task . e . g resque : work - : queue e . g . * - : count e . g . 3 - : interval e . g . 5 - : verbose e . g . true - : vverbose e . g . true - : trace e . g . true - : stop_signal e . g . : QUIT or : SIGQUIT [CODESPLIT] def start stop UI . info 'Starting up resque...' UI . info [ cmd , env . map { | v | v . join ( '=' ) } ] . join ( ' ' ) # launch Resque worker @pid = spawn ( env , cmd ) end


Input: We pass ourselves as both input and output to Ernicorn . process which calls the following blocking read / write methods . [CODESPLIT] def read ( len ) data = '' while data . bytesize < len data << @client . kgio_read! ( len - data . bytesize ) end data end


Input: TODO : move into separate class so we don t pollute controller . [CODESPLIT] def consume! ( model , options = { } ) content_type = request . content_type format = Mime :: Type . lookup ( content_type ) . try ( :symbol ) or raise UnsupportedMediaType . new ( "Cannot consume unregistered media type '#{content_type.inspect}'" ) parsing_method = compute_parsing_method ( format ) representer = prepare_model_for ( format , model , options ) representer . send ( parsing_method , incoming_string , options ) # e.g. from_json("...") model end


Input: Central entry - point for finding the appropriate representer . [CODESPLIT] def representer_for ( format , model , options = { } ) options . delete ( :represent_with ) || self . class . represents_options . for ( format , model , controller_path ) end


Input: Article Show [CODESPLIT] def show @article_post = Phcpress :: Article :: Post . friendly . find ( params [ :id ] ) @versions = Phcpress :: PostVersions . where ( item_id : params [ :id ] , item_type : 'Phcpress::Article::Post' ) end


Input: POST [CODESPLIT] def create @article_post = Phcpress :: Article :: Post . new ( article_post_params ) @article_post . user_id = current_user . id @article_post . org_id = current_user . org_id if @article_post . save redirect_to article_posts_url , notice : 'Post was successfully created.' else render :new end end


Input: Categories Show [CODESPLIT] def show @article_category = Phcpress :: Article :: Category . friendly . find ( params [ :id ] ) @versions = Phcpress :: CategoryVersions . where ( item_id : params [ :id ] , item_type : 'Phcpress::Article::Category' ) end


Input: POST [CODESPLIT] def create @article_category = Phcpress :: Article :: Category . new ( article_category_params ) @article_category . user_id = current_user . id @article_category . org_id = current_user . org_id if @article_category . save redirect_to article_categories_url , notice : 'Category was successfully created.' else render :new end end


Input: Called when the new method is invoked Sets a variable field that can be recalled [CODESPLIT] def variable_text_field ( x , y , params = { } ) x = 0 unless numeric? ( x ) y = 0 unless numeric? ( y ) options = { height : 0.1 , width : 0.1 } . merge! ( params ) # update the variable field count self . variable_fields_count += 1 label_data . push ( '^FO' + Integer ( x * printer_dpi ) . to_s + ',' + Integer ( y * printer_dpi ) . to_s ) if params [ :orientation ] == :landscape label_data . push ( '^A0N,' ) else label_data . push ( '^A0B,' ) end label_data . push ( Integer ( options [ :height ] * printer_dpi ) . to_s + ',' + Integer ( options [ :width ] * printer_dpi ) . to_s + '^FN' + variable_fields_count . to_s + '^FS' ) # return unless label_height > 0 && label_width > 0 # pdf.text_box '{Variable Field ' + variable_fields_count.to_s + '}', #              at: [Integer(x * pdf_dpi), Integer(label_width * pdf_dpi) - #              Integer(y * pdf_dpi) - #              Integer(options[:height] / 10) * pdf_dpi], #              size: Integer(options[:height] * pdf_dpi) if label_height && #              label_width end


Input: Set the home position of the label All other X and Y coordinates are relative to this [CODESPLIT] def home_position ( x , y ) x = 0 unless numeric? ( x ) y = 0 unless numeric? ( y ) label_data . push ( '^LH' + x . to_s + ',' + y . to_s ) end


Input: Draws a square border on dot in width [CODESPLIT] def draw_border ( x , y , height , width ) return unless numeric? ( height ) && numeric? ( width ) x = 0 unless numeric? ( x ) y = 0 unless numeric? ( y ) label_data . push ( '^FO' + Integer ( x * printer_dpi ) . to_s + ',' + Integer ( y * printer_dpi ) . to_s + '^GB' + Integer ( height * printer_dpi ) . to_s + ',' + Integer ( width * printer_dpi ) . to_s + ',1^FS' ) # draw_rectangle(x * pdf_dpi, y * pdf_dpi, height * pdf_dpi, width * pdf_dpi) end


Input: Prints text [CODESPLIT] def text_field ( text , x , y , params = { } ) x = 0 unless numeric? ( x ) y = 0 unless numeric? ( y ) options = { height : 0.1 , width : 0.1 } . merge! ( params ) label_data . push ( '^FO' + Integer ( x * printer_dpi ) . to_s + ',' + Integer ( y * printer_dpi ) . to_s ) if params [ :orientation ] == :landscape label_data . push ( '^A0N,' ) else label_data . push ( '^A0B,' ) end label_data . push ( Integer ( options [ :height ] * printer_dpi ) . to_s + ',' + Integer ( options [ :width ] * printer_dpi ) . to_s + '^FD' + text + '^FS' ) # return unless label_height > 0 && label_width > 0 # pdf.text_box text, at: [x, label_width - y - #                    Integer((options[:height] * pdf_dpi) / 10)], #                    size: (options[:height] * #                    pdf_dpi) if label_height && label_width end


Input: Prints a bar code in barcode39 font [CODESPLIT] def bar_code_39 ( bar_code_string , x , y , params = { } ) x = 0 unless numeric? ( x ) y = 0 unless numeric? ( y ) label_data . push ( '^FO' + Integer ( x * printer_dpi ) . to_s + ',' + Integer ( y * printer_dpi ) . to_s + '^B3N,N,20,N,N^FD' + bar_code_string + '^FS' ) # return unless label_height && label_width # options = { height: 20 }.merge!(params) { |key, v1, v2| v1 } # draw_bar_code_39(bar_code_string, Integer(x * pdf_dpi), #                  Integer(y * pdf_dpi), (options[:height] * pdf_dpi)) end


Input: Prints a bar code in barcode39 font [CODESPLIT] def bar_code_128 ( bar_code_string , x , y , params = { } ) x = 0 unless numeric? ( x ) y = 0 unless numeric? ( y ) height = numeric? ( params [ :height ] ) ? params [ :height ] : 0.2 interpretation = params [ :interpretation ] == :true ? 'Y' : 'N' interpretation_location = params [ :interpretation_location ] == :above ? 'Y' : 'N' check_digit = params [ :check_digit ] == :true ? 'Y' : 'N' mode = { :ucc_case => 'U' , :auto => 'A' , :ucc_ean => 'D' } [ params [ :mode ] ] || 'N' orientation = { :portrait => 'R' , 90 => 'R' , 180 => 'I' , 270 => 'B' } [ params [ :orientation ] ] || 'N' label_data . push ( '^FO' + Integer ( x * printer_dpi ) . to_s + ',' + Integer ( y * printer_dpi ) . to_s + '^BC' + orientation + ',' + Integer ( height * printer_dpi ) . to_s + ',' + interpretation + ',' + interpretation_location + ',' + check_digit + ',' + mode + '^FD' + bar_code_string + '^FS' ) # return unless label_height && label_width # options = { height: 20 }.merge!(params) { |key, v1, v2| v1 } # draw_bar_code128_(bar_code_string, Integer(x * pdf_dpi), #                   Integer(y * pdf_dpi), (options[:height] * pdf_dpi)) end


Input: Prints a bar code in barcode39 font [CODESPLIT] def bar_code_qr ( bar_code_string , x , y , params = { } ) x = 0 unless numeric? ( x ) y = 0 unless numeric? ( y ) magnification = numeric? ( params [ :magnification ] ) ? params [ :magnification ] : default_qr_code_magnification error_correction = { :ultra => 'H' , :high => 'Q' , :standard => 'M' , :density => 'L' } [ params [ :error_correction ] ] || ( params [ :error_correction ] ) . nil? ? 'Q' : 'M' mask = numeric? ( params [ :mask ] ) ? params [ :mask ] : 7 model = { 1 => 1 , :standard => 1 , 2 => 2 , :enhanced => 2 } [ params [ :model ] ] || 2 label_data . push ( '^FO' + Integer ( x * printer_dpi ) . to_s + ',' + Integer ( y * printer_dpi ) . to_s + '^BQN,' + Integer ( model ) . to_s + ',' + Integer ( magnification ) . to_s + ',' + error_correction + ',' + Integer ( mask ) . to_s + '^FD' + error_correction + 'A,' + bar_code_string + '^FS' ) # return unless label_height && label_width # options = { height: 20 }.merge!(params) { |key, v1, v2| v1 } # draw_bar_code128_(bar_code_string, Integer(x * pdf_dpi), #                   Integer(y * pdf_dpi), (options[:height] * pdf_dpi)) end


Input: Some barcodes such as QR codes may change document defaults . These may be reset to the document defaults . [CODESPLIT] def reset_barcode_fields_to_default label_data . push ( '^BY' + Integer ( self . barcode_default_module_width ) . to_s + ',' + Float ( self . barcode_default_width_ratio ) . to_s + ',' + Integer ( self . barcode_default_height ) . to_s ) end


Input: Draws the PDF rectangle ( border ) [CODESPLIT] def draw_rectangle ( x , y , height , width ) return unless label_height > 0 && label_width > 0 pdf . stroke_axis pdf . stroke do pdf . rectangle [ x * pdf_dpi , label_width - ( y * pdf_dpi ) - ( width * pdf_dpi ) ] , height , ( width * pdf_dpi ) * - 1 end end


Input: Draws the PDF bar code 39 [CODESPLIT] def draw_bar_code_39 ( bar_code_string , x , y , height ) return unless label_height > 0 && label_width > 0 pdf . bounding_box [ x , Integer ( label_width ) - y - ( height * pdf_dpi ) ] , width : ( height * pdf_dpi ) do barcode = Barby :: Code39 . new ( bar_code_string ) barcode . annotate_pdf ( pdf , height : ( height * pdf_dpi ) ) end end


Input: Called when the new method is invoked Adds a variable that is to be applied to the saved template [CODESPLIT] def add_field ( value ) return if value . nil? return if value . strip . empty? # Increment the variable field count self . variable_fields_count += 1 # Add the field label_data . push ( '^FN' + variable_fields_count . to_s + '^FD' + value + '^FS' ) end


Input: Builds a new slug . [CODESPLIT] def build_slug if localized? begin orig_locale = I18n . locale all_locales . each do | target_locale | I18n . locale = target_locale apply_slug end ensure I18n . locale = orig_locale end else apply_slug end true end


Input: Returns true if object is a new record and slugs are present [CODESPLIT] def new_with_slugs? if localized? # We need to check if slugs are present for the locale without falling back # to a default new_record? && _slugs_translations . fetch ( I18n . locale . to_s , [ ] ) . any? else new_record? && _slugs . present? end end


Input: Returns true if object has been persisted and has changes in the slug [CODESPLIT] def persisted_with_slug_changes? if localized? changes = _slugs_change return ( persisted? && false ) if changes . nil? # ensure we check for changes only between the same locale original = changes . first . try ( :fetch , I18n . locale . to_s , nil ) compare = changes . last . try ( :fetch , I18n . locale . to_s , nil ) persisted? && original != compare else persisted? && _slugs_changed? end end


Input: Return all possible locales for model Avoiding usage of I18n . available_locales in case the user hasn t set it properly or is doing something crazy but at the same time we need a fallback in case the model doesn t have any localized attributes at all ( extreme edge case ) . [CODESPLIT] def all_locales locales = slugged_attributes . map { | attr | send ( "#{attr}_translations" ) . keys if respond_to? ( "#{attr}_translations" ) } . flatten . compact . uniq locales = I18n . available_locales if locales . empty? locales end


Input: Internal : Assigns the : request_id thread - local variable and cleans up all the request - local variables after the request . [CODESPLIT] def call ( env ) Thread . current [ :request_id ] = extract_request_id ( env ) @app . call ( env ) ensure RequestLocals . clear! Thread . current [ :request_id ] = nil end


Input: Return the distance of time in words from the given from_time to the specified to_time . If to_time is not specified then Time . now is used . By default seconds are included ... set the include_seconds argument to false to disable the seconds . [CODESPLIT] def distance_of_time_in_words ( from_time , to_time = Time . now ) from_time = from_time . to_time if from_time . respond_to? ( :to_time ) to_time = to_time . to_time if to_time . respond_to? ( :to_time ) seconds = ( to_time - from_time ) . round distance_in_days = ( seconds / ( 60 * 60 * 24 ) ) . round seconds = seconds % ( 60 * 60 * 24 ) distance_in_hours = ( seconds / ( 60 * 60 ) ) . round seconds = seconds % ( 60 * 60 ) distance_in_minutes = ( seconds / 60 ) . round seconds = seconds % 60 distance_in_seconds = seconds s = '' s << "#{distance_in_days} days," if distance_in_days > 0 s << "#{distance_in_hours} hours, " if distance_in_hours > 0 s << "#{distance_in_minutes} minutes, " if distance_in_minutes > 0 s << "#{distance_in_seconds} seconds" s end


Input: Get the approximate disntance of time in words from the given from_time to the the given to_time . If to_time is not specified then it is set to Time . now . By default seconds are included ... set the include_seconds argument to false to disable the seconds . [CODESPLIT] def approximate_distance_of_time_in_words ( from_time , to_time = Time . now , include_seconds = true ) from_time = from_time . to_time if from_time . respond_to? ( :to_time ) to_time = to_time . to_time if to_time . respond_to? ( :to_time ) distance_in_minutes = ( ( ( to_time - from_time ) . abs ) / 60 ) . round distance_in_seconds = ( ( to_time - from_time ) . abs ) . round case distance_in_minutes when 0 .. 1 return ( distance_in_minutes == 0 ) ? 'less than a minute' : '1 minute' unless include_seconds case distance_in_seconds when 0 .. 4 then 'less than 5 seconds' when 5 .. 9 then 'less than 10 seconds' when 10 .. 19 then 'less than 20 seconds' when 20 .. 39 then 'half a minute' when 40 .. 59 then 'less than a minute' else '1 minute' end when 2 .. 44 then "#{distance_in_minutes} minutes" when 45 .. 89 then 'about 1 hour' when 90 .. 1439 then "about #{(distance_in_minutes.to_f / 60.0).round} hours" when 1440 .. 2879 then '1 day' when 2880 .. 43199 then "#{(distance_in_minutes / 1440).round} days" when 43200 .. 86399 then 'about 1 month' when 86400 .. 525959 then "#{(distance_in_minutes / 43200).round} months" when 525960 .. 1051919 then 'about 1 year' else "over #{(distance_in_minutes / 525960).round} years" end end


Input: First attempt at centralizing error notifications [CODESPLIT] def track_error ( control , msg ) errors << msg control . error_handlers . each do | handler | handler . call ( msg ) end end


Input:
Process a file control object or batch object . Acceptable values for file are : * Path to a file * File object * ETL :: Control :: Control instance * ETL :: Batch :: Batch instance [CODESPLIT] def process ( file ) case file when String process ( File . new ( file ) ) when File case file . path when / \. \. / ; process_control ( file ) when / \. \. / ; process_batch ( file ) else raise RuntimeError , "Unsupported file type - #{file.path}" end when ETL :: Control :: Control process_control ( file ) when ETL :: Batch :: Batch process_batch ( file ) else raise RuntimeError , "Process object must be a String, File, Control
        instance or Batch instance" end end


Input: Process the specified batch file [CODESPLIT] def process_batch ( batch ) batch = ETL :: Batch :: Batch . resolve ( batch , self ) say "Processing batch #{batch.file}" ETL :: Engine . batch = ETL :: Execution :: Batch . create! ( :batch_file => batch . file , :status => 'executing' ) batch . execute ETL :: Engine . batch . completed_at = Time . now ETL :: Engine . batch . status = ( errors . length > 0 ? 'completed with errors' : 'completed' ) ETL :: Engine . batch . save! end


Input: Process the specified control file [CODESPLIT] def process_control ( control ) control = ETL :: Control :: Control . resolve ( control ) say_on_own_line "Processing control #{control.file}" ETL :: Engine . job = ETL :: Execution :: Job . new . tap do | job | job . control_file = control . file job . status = 'executing' job . batch_id = ETL :: Engine . batch ? ETL :: Engine . batch . id : nil job . save! end execute_dependencies ( control ) start_time = Time . now pre_process ( control ) sources = control . sources destinations = control . destinations say "Skipping bulk import" if Engine . skip_bulk_import sources . each do | source | Engine . current_source = source Engine . logger . debug "Processing source #{source.inspect}" say "Source: #{source}" say "Limiting enabled: #{Engine.limit}" if Engine . limit != nil say "Offset enabled: #{Engine.offset}" if Engine . offset != nil source . each_with_index do | row , index | # Break out of the row loop if the +Engine.limit+ is specified and  # the number of rows read exceeds that value. if Engine . limit != nil && Engine . rows_read >= Engine . limit puts "Reached limit of #{Engine.limit}" break end Engine . logger . debug "Row #{index}: #{row.inspect}" Engine . rows_read += 1 Engine . current_source_row = index + 1 say_without_newline "." if Engine . realtime_activity && index > 0 && index % 1000 == 0 # At this point a single row may be turned into multiple rows via row  # processors all code after this line should work with the array of  # rows rather than the single row rows = [ row ] t = Benchmark . realtime do begin Engine . logger . debug "Processing after read" control . after_read_processors . each do | processor | processed_rows = [ ] rows . each do | row | processed_rows << processor . process ( row ) unless empty_row? ( row ) end rows = processed_rows . flatten . compact end rescue => e msg = "Error processing rows after read from #{Engine.current_source} on line #{Engine.current_source_row}: #{e}" # TODO - track more information: row if possible, full exception... track_error ( control , msg ) Engine . logger . error ( msg ) e . backtrace . each { | line | Engine . logger . error ( line ) } exceeded_error_threshold? ( control ) ? break : next end end benchmarks [ :after_reads ] += t unless t . nil? t = Benchmark . realtime do begin Engine . logger . debug "Executing transforms" rows . each do | row | # only do the transform if there is a row unless empty_row? ( row ) control . transforms . each do | transform | name = transform . name . to_sym row [ name ] = transform . transform ( name , row [ name ] , row ) end end end rescue ResolverError => e Engine . logger . error ( e . message ) track_error ( control , e . message ) rescue => e msg = "Error transforming from #{Engine.current_source} on line #{Engine.current_source_row}: #{e}" track_error ( control , msg ) Engine . logger . error ( msg ) e . backtrace . each { | line | Engine . logger . error ( line ) } ensure begin exceeded_error_threshold? ( control ) ? break : next rescue => inner_error puts inner_error end end end benchmarks [ :transforms ] += t unless t . nil? t = Benchmark . realtime do begin # execute row-level "before write" processing Engine . logger . debug "Processing before write" control . before_write_processors . each do | processor | processed_rows = [ ] rows . each do | row | processed_rows << processor . process ( row ) unless empty_row? ( row ) end rows = processed_rows . flatten . compact end rescue => e msg = "Error processing rows before write from #{Engine.current_source} on line #{Engine.current_source_row}: #{e}" track_error ( control , msg ) Engine . logger . error ( msg ) e . backtrace . each { | line | Engine . logger . error ( line ) } exceeded_error_threshold? ( control ) ? break : next end end benchmarks [ :before_writes ] += t unless t . nil? t = Benchmark . realtime do begin # write the row to the destination destinations . each_with_index do | destination , index | Engine . current_destination = destination rows . each do | row | destination . write ( row ) Engine . rows_written += 1 if index == 0 end end rescue => e msg = "Error writing to #{Engine.current_destination}: #{e}" track_error ( control , msg ) Engine . logger . error msg e . backtrace . each { | line | Engine . logger . error ( line ) } exceeded_error_threshold? ( control ) ? break : next end end benchmarks [ :writes ] += t unless t . nil? end if exceeded_error_threshold? ( control ) say_on_own_line "Exiting due to exceeding error threshold: #{control.error_threshold}" ETL :: Engine . exit_code = 1 end end destinations . each do | destination | destination . close end say_on_own_line "Executing before post-process screens" begin execute_screens ( control ) rescue FatalScreenError => e say "Fatal screen error during job execution: #{e.message}" ETL :: Engine . exit_code = 2 rescue ScreenError => e say "Screen error during job execution: #{e.message}" return else say "Screens passed" end post_process ( control ) if sources . length > 0 say_on_own_line "Read #{Engine.rows_read} lines from sources" end if destinations . length > 0 say "Wrote #{Engine.rows_written} lines to destinations" end say_on_own_line "Executing after post-process screens" begin execute_screens ( control , :after_post_process ) rescue FatalScreenError => e say "Fatal screen error during job execution: #{e.message}" ETL :: Engine . exit_code = 3 rescue ScreenError => e say "Screen error during job execution: #{e.message}" return else say "Screens passed" end say_on_own_line "Completed #{control.file} in #{distance_of_time_in_words(start_time)} with #{errors.length} errors." say "Processing average: #{Engine.average_rows_per_second} rows/sec)" say "Avg after_reads: #{Engine.rows_read/benchmarks[:after_reads]} rows/sec" if benchmarks [ :after_reads ] > 0 say "Avg before_writes: #{Engine.rows_read/benchmarks[:before_writes]} rows/sec" if benchmarks [ :before_writes ] > 0 say "Avg transforms: #{Engine.rows_read/benchmarks[:transforms]} rows/sec" if benchmarks [ :transforms ] > 0 say "Avg writes: #{Engine.rows_read/benchmarks[:writes]} rows/sec" if benchmarks [ :writes ] > 0 # say "Avg time writing execution records: #{ETL::Execution::Record.average_time_spent}" #  # ETL::Transform::Transform.benchmarks.each do |klass, t| #         say "Avg #{klass}: #{Engine.rows_read/t} rows/sec" #       end ActiveRecord :: Base . verify_active_connections! ETL :: Engine . job . completed_at = Time . now ETL :: Engine . job . status = ( errors . length > 0 ? 'completed with errors' : 'completed' ) ETL :: Engine . job . save! end


Input: Execute all preprocessors [CODESPLIT] def pre_process ( control ) Engine . logger . debug "Pre-processing #{control.file}" control . pre_processors . each do | processor | processor . process end Engine . logger . debug "Pre-processing complete" end


Input: Execute all postprocessors [CODESPLIT] def post_process ( control ) say_on_own_line "Executing post processes" Engine . logger . debug "Post-processing #{control.file}" control . post_processors . each do | processor | processor . process end Engine . logger . debug "Post-processing complete" say "Post-processing complete" end


Input: Execute all dependencies [CODESPLIT] def execute_dependencies ( control ) Engine . logger . debug "Executing dependencies" control . dependencies . flatten . each do | dependency | case dependency when Symbol f = dependency . to_s + '.ctl' Engine . logger . debug "Executing dependency: #{f}" say "Executing dependency: #{f}" process ( f ) when String Engine . logger . debug "Executing dependency: #{f}" say "Executing dependency: #{f}" process ( dependency ) else raise "Invalid dependency type: #{dependency.class}" end end end


Input: Execute all screens [CODESPLIT] def execute_screens ( control , timing = :before_post_process ) screens = case timing when :after_post_process control . after_post_process_screens else # default to before post-process screens control . screens end [ :fatal , :error , :warn ] . each do | type | screens [ type ] . each do | block | begin block . call rescue => e case type when :fatal raise FatalScreenError , e when :error raise ScreenError , e when :warn say "Screen warning: #{e}" end end end end end


Input: add new field which will be saved into redis * name - name of your variable * type - type of your variable ( : integer : float : string : array : hash ) * ( default ) - default value of your variable [CODESPLIT] def redis_field name , type , default = nil redis_user_field_config << name # remember field to save into redis redis_fields_config [ name ] = type # remember field default value redis_fields_defaults_config [ name ] = default define_attribute_method name end


Input: set redis key which will be used for storing model [CODESPLIT] def redis_key * fields @redis_key_config = fields . flatten validate_redis_key #own specification of redis key - delete autoincrement remove_redis_autoincrement_key unless redis_user_field_config . include? ( :id ) || @redis_key_config . include? ( :id ) # automaticaly add all fields from key to validation # if any of fields in redis key is nil # then prevent to save it @redis_key_config . each do | field | validates field , :presence => :true if field != :id end end


Input: set redis model to normalize redis keys [CODESPLIT] def redis_key_normalize * metrics @redis_key_normalize_conf ||= [ ] metrics . each do | metric | raise ArgumentError , "Please provide valid normalization: #{VALID_NORMALIZATIONS.join(", ")}" unless VALID_NORMALIZATIONS . include? ( metric ) @redis_key_normalize_conf << metric end end


Input: store informations about redis aliases [CODESPLIT] def redis_alias name , main_fields , name_of_field_for_order = nil , name_of_field_for_args = nil #set fields if they are not allready set! if name_of_field_for_order && name_of_field_for_args redis_field name_of_field_for_order , :array , [ ] unless redis_fields_config . has_key? ( name_of_field_for_order ) redis_field name_of_field_for_args , :hash , { } unless redis_fields_config . has_key? ( name_of_field_for_args ) end @redis_alias_config ||= { } #add specification of dynamic alias @redis_alias_config [ name ] = { main_fields : main_fields , order_field : name_of_field_for_order , args_field : name_of_field_for_args , } #create alias methods for find and get (find_by_name, get_by_name) create_class_alias_method ( name ) end


Input: set old arguments [CODESPLIT] def store_redis_keys args = to_arg #store main key redis_old_keys [ :key ] = self . class . generate_key ( args ) #store main key #store alias keys redis_old_keys [ :aliases ] = [ ] redis_alias_config . each do | alias_name , fields | redis_old_keys [ :aliases ] << redis_alias_key ( alias_name ) if valid_alias_key? alias_name end end


Input: old method to initialize redis model extenstion Usage : REDIS_MODEL_CONF = { : fields = > { : integer = > : to_i : boolean = > : to_bool : string = > : to_s : symbol = > : to_sym } : required = > [ : integer : string ] : redis_key = > [ : string : symbol ] : redis_aliases = > { : token = > [ : symbol ] } # ( default is true ) if true all nil values will not be saved into redis # there should be problem when you want to set some value to nil and same # it will not be saved ( use false to prevent this ) : reject_nil_values = > false } include RedisModel initialize_redis_model_methods REDIS_MODEL_CONF [CODESPLIT] def initialize_redis_model_methods conf puts "WARNING: This initilization method is deprecated and will be removed in future! \n Please read documentation how to change your model to use new initialization methods" remove_redis_autoincrement_key @conf = { :reject_nil_values => true } . merge ( conf ) #take all fields and make methods for them conf [ :fields ] . each do | name , action | redis_fields_config [ name ] = TYPE_TRANSLATIONS . invert [ action ] redis_fields_defaults_config [ name ] = nil # define getter method for field define_method "#{name}" do value_get name end # define setter method for field define_method "#{name}=" do | new_value | value_set name , new_value end # define exists? method for field define_method "#{name}?" do value_get ( name ) && ! value_get ( name ) . blank? ? true : false end end # save nil values? redis_save_fields_with_nil false if ! conf . has_key? ( :reject_nil_values ) || conf [ :reject_nil_values ] == true # save into class config about redis key @redis_key_config = conf [ :redis_key ] #validate presence of all fields in key @required_config = ( @redis_key_config | conf [ :required ] ) ( @redis_key_config | conf [ :required ] ) . each do | field | validates field , :presence => :true end # save into class config about redis keys @redis_alias_config = { } conf [ :redis_aliases ] . each do | key , fields | @redis_alias_config [ key ] = { main_fields : fields , order_field : nil , args_field : nil , } end end


Input: get config hash [CODESPLIT] def conf fields = { } redis_fields_config . each do | key , type | fields [ key ] = TYPE_TRANSLATIONS [ type ] if TYPE_TRANSLATIONS . has_key? ( type ) end { fields : fields , required : @required_config . sort , redis_key : redis_key_config , redis_aliases : redis_alias_config . inject ( { } ) { | o , ( k , v ) | o [ k ] = v [ :main_fields ] ; o } , reject_nil_values : ! redis_save_fields_with_nil_conf , } end