idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
2,400
def remove_by_id ( clazz , * ids ) class_name = if clazz . is_a? ( Class ) clazz . name else clazz . to_s end indexer . remove_by_id ( class_name , ids ) end
See Sunspot . remove_by_id
2,401
def remove_all ( * classes ) classes . flatten! if classes . empty? @deletes += 1 indexer . remove_all else @deletes += classes . length classes . each { | clazz | indexer . remove_all ( clazz ) } end end
See Sunspot . remove_all
2,402
def connection @connection ||= self . class . connection_class . connect ( url : config . solr . url , read_timeout : config . solr . read_timeout , open_timeout : config . solr . open_timeout , proxy : config . solr . proxy , update_format : config . solr . update_format || :xml ) end
Retrieve the Solr connection for this session creating one if it does not already exist .
2,403
def dynamic_fields fields = [ ] variant_combinations . each do | field_variants | FIELD_TYPES . each do | type | fields << DynamicField . new ( type , field_variants ) end end fields end
DynamicField instances representing all the available types and variants
2,404
def to_xml template_path = File . join ( File . dirname ( __FILE__ ) , '..' , '..' , 'templates' , 'schema.xml.erb' ) template_text = File . read ( template_path ) erb = if RUBY_VERSION >= '2.6' ERB . new ( template_text , trim_mode : '-' ) else ERB . new ( template_text , nil , '-' ) end erb . result ( binding ) end
Return an XML representation of this schema using the ERB template
2,405
def variant_combinations combinations = [ ] 0 . upto ( 2 ** FIELD_VARIANTS . length - 1 ) do | b | combinations << combination = [ ] FIELD_VARIANTS . each_with_index do | variant , i | combination << variant if b & 1 << i > 0 end end combinations end
All of the possible combinations of variants
2,406
def text_fields ( field_name ) if text_fields = text_fields_hash [ field_name . to_sym ] text_fields . to_a else raise ( UnrecognizedFieldError , "No text field configured for #{@types * ', '} with name '#{field_name}'" ) end end
Get a text field object by its public name . A field will be returned if it is configured for any of the enclosed types .
2,407
def text_fields_hash @text_fields_hash ||= setups . inject ( { } ) do | hash , setup | setup . all_text_fields . each do | text_field | ( hash [ text_field . name ] ||= Set . new ) << text_field end hash end end
Return a hash of field names to text field objects containing all fields that are configured for any of the types enclosed .
2,408
def fields_hash @fields_hash ||= begin field_sets_hash = Hash . new { | h , k | h [ k ] = Set . new } @types . each do | type | Setup . for ( type ) . fields . each do | field | field_sets_hash [ field . name . to_sym ] << field end end fields_hash = { } field_sets_hash . each_pair do | field_name , set | if set . length == 1 fields_hash [ field_name ] = set . to_a . first end end fields_hash end end
Return a hash of field names to field objects containing all fields that are common to all of the classes enclosed . In order for fields to be common they must be of the same type and have the same value for allow_multiple? and stored? . This method is memoized .
2,409
def add_text_field_factory ( name , options = { } , & block ) stored , more_like_this = options [ :stored ] , options [ :more_like_this ] field_factory = FieldFactory :: Static . new ( name , Type :: TextType . instance , options , & block ) @text_field_factories [ name ] = field_factory @text_field_factories_cache [ field_factory . name ] = field_factory if stored @stored_field_factories_cache [ field_factory . name ] << field_factory end if more_like_this @more_like_this_field_factories_cache [ field_factory . name ] << field_factory end end
Add field_factories for fulltext search
2,410
def add_dynamic_field_factory ( name , type , options = { } , & block ) stored , more_like_this = options [ :stored ] , options [ :more_like_this ] field_factory = FieldFactory :: Dynamic . new ( name , type , options , & block ) @dynamic_field_factories [ field_factory . signature ] = field_factory @dynamic_field_factories_cache [ field_factory . name ] = field_factory if stored @stored_field_factories_cache [ field_factory . name ] << field_factory end if more_like_this @more_like_this_field_factories_cache [ field_factory . name ] << field_factory end end
Add dynamic field_factories
2,411
def all_more_like_this_fields @more_like_this_field_factories_cache . values . map do | field_factories | field_factories . map { | field_factory | field_factory . build } end . flatten end
Return all more_like_this fields
2,412
def all_field_factories all_field_factories = [ ] all_field_factories . concat ( field_factories ) . concat ( text_field_factories ) . concat ( dynamic_field_factories ) all_field_factories end
Get all static dynamic and text field_factories associated with this setup as well as all inherited field_factories
2,413
def add_atomic_update ( clazz , updates = { } ) documents = updates . map { | id , m | prepare_atomic_update ( clazz , id , m ) } add_batch_documents ( documents ) end
Construct a representation of the given class instances for atomic properties update and send it to the connection for indexing
2,414
def remove ( * models ) @connection . delete_by_id ( models . map { | model | Adapters :: InstanceAdapter . adapt ( model ) . index_id } ) end
Remove the given model from the Solr index
2,415
def remove_by_id ( class_name , * ids ) ids . flatten! @connection . delete_by_id ( ids . map { | id | Adapters :: InstanceAdapter . index_id_for ( class_name , id ) } ) end
Remove the model from the Solr index by specifying the class and ID
2,416
def prepare_full_update ( model ) document = document_for_full_update ( model ) setup = setup_for_object ( model ) if boost = setup . document_boost_for ( model ) document . attrs [ :boost ] = boost end setup . all_field_factories . each do | field_factory | field_factory . populate_document ( document , model ) end document end
Convert documents into hash of indexed properties
2,417
def document_for_full_update ( model ) RSolr :: Xml :: Document . new ( id : Adapters :: InstanceAdapter . adapt ( model ) . index_id , type : Util . superclasses_for ( model . class ) . map ( & :name ) ) end
All indexed documents index and store the + id + and + type + fields . These methods construct the document hash containing those key - value pairs .
2,418
def analyze ( phone , passed_country ) country = country_or_default_country passed_country result = parse_country ( phone , country ) d_result = case when result && result . values . find { | e | e [ :valid ] . any? } when passed_country . nil? detect_and_parse ( phone , country ) when country_can_dp? ( country ) parse_country ( changed_dp_phone ( country , phone ) , country ) end better_result ( result , d_result ) end
parses provided phone if it is valid for country data and returns result of analyze
2,419
def better_result ( base_result , result = nil ) base_result ||= { } return base_result unless result return result unless base_result . values . find { | e | e [ :possible ] . any? } return result if result . values . find { | e | e [ :valid ] . any? } base_result end
method checks which result is better to return
2,420
def with_replaced_national_prefix ( phone , data ) return phone unless data [ Core :: NATIONAL_PREFIX_TRANSFORM_RULE ] pattern = cr ( "^(?:#{data[Core::NATIONAL_PREFIX_FOR_PARSING]})" ) match = phone . match pattern if match && match . captures . compact . size > 0 phone . gsub ( pattern , data [ Core :: NATIONAL_PREFIX_TRANSFORM_RULE ] ) else phone end end
replacing national prefix to simplified format
2,421
def parse_country ( phone , country ) data = Phonelib . phone_data [ country ] return nil unless data e164 = convert_to_e164 with_replaced_national_prefix ( phone , data ) , data return analyze ( e164 [ 1 .. - 1 ] , nil ) if Core :: PLUS_SIGN == e164 [ 0 ] parse_single_country e164 , data end
trying to parse phone for single country including international prefix check for provided country
2,422
def parse_single_country ( e164 , data ) valid_match = phone_match_data? ( e164 , data ) if valid_match national_and_data ( data , valid_match ) else possible_match = phone_match_data? ( e164 , data , true ) possible_match && national_and_data ( data , possible_match , true ) end end
method checks if phone is valid against single provided country data
2,423
def detect_and_parse ( phone , country ) result = { } Phonelib . phone_data . each do | key , data | parsed = parse_single_country ( phone , data ) if ( ! Phonelib . strict_double_prefix_check || key == country ) && double_prefix_allowed? ( data , phone , parsed && parsed [ key ] ) parsed = parse_single_country ( changed_dp_phone ( key , phone ) , data ) end result . merge! ( parsed ) unless parsed . nil? end result end
method tries to detect what is the country for provided phone
2,424
def convert_to_e164 ( phone , data ) match = phone . match full_regex_for_data ( data , Core :: VALID_PATTERN , ! original_starts_with_plus? ) case when match "#{data[Core::COUNTRY_CODE]}#{match.to_a.last}" when phone . match ( cr ( "^#{data[Core::INTERNATIONAL_PREFIX]}" ) ) phone . sub ( cr ( "^#{data[Core::INTERNATIONAL_PREFIX]}" ) , Core :: PLUS_SIGN ) when original_starts_with_plus? && phone . start_with? ( data [ Core :: COUNTRY_CODE ] ) phone else "#{data[Core::COUNTRY_CODE]}#{phone}" end end
Create phone representation in e164 format
2,425
def national_and_data ( data , country_match , not_valid = false ) result = data . select { | k , _v | k != :types && k != :formats } phone = country_match . to_a . last result [ :national ] = phone result [ :format ] = number_format ( phone , data [ Core :: FORMATS ] ) result . merge! all_number_types ( phone , data [ Core :: TYPES ] , not_valid ) result [ :valid ] = [ ] if not_valid { result [ :id ] => result } end
returns national number and analyzing results for provided phone number
2,426
def all_number_types ( phone , data , not_valid = false ) response = { valid : [ ] , possible : [ ] } types_for_check ( data ) . each do | type | possible , valid = get_patterns ( data , type ) valid_and_possible , possible_result = number_valid_and_possible? ( phone , possible , valid , not_valid ) response [ :possible ] << type if possible_result response [ :valid ] << type if valid_and_possible end sanitize_fixed_mobile ( response ) end
Returns all valid and possible phone number types for currently parsed phone for provided data hash .
2,427
def number_format ( national , format_data ) format_data && format_data . find do | format | ( format [ Core :: LEADING_DIGITS ] . nil? || national . match ( cr ( "^(#{format[Core::LEADING_DIGITS]})" ) ) ) && national . match ( cr ( "^(#{format[Core::PATTERN]})$" ) ) end || Core :: DEFAULT_NUMBER_FORMAT end
Gets matched number formatting rule or default one
2,428
def get_patterns ( all_patterns , type ) type = Core :: FIXED_LINE if type == Core :: FIXED_OR_MOBILE patterns = all_patterns [ type ] if patterns [ type_regex ( patterns , Core :: POSSIBLE_PATTERN ) , type_regex ( patterns , Core :: VALID_PATTERN ) ] else [ nil , nil ] end end
Returns possible and valid patterns for validation for provided type
2,429
def vanity_converted ( phone ) return phone unless Phonelib . vanity_conversion ( phone || '' ) . gsub ( cr ( '[a-zA-Z]' ) ) do | c | c . upcase! n = ( c . ord - 65 ) / 3 n -= 1 if c . match ( Core :: VANITY_4_LETTERS_KEYS_REGEX ) ( n + 2 ) . to_s end end
converts symbols in phone to numbers
2,430
def passed_country ( country ) code = country_prefix ( country ) if Core :: PLUS_SIGN == @original [ 0 ] && code && ! sanitized . start_with? ( code ) country = nil end country end
defines if to validate against single country or not
2,431
def country_prefix ( country ) country = country . to_s . upcase Phonelib . phone_data [ country ] && Phonelib . phone_data [ country ] [ Core :: COUNTRY_CODE ] end
returns country prefix for provided country or nil
2,432
def country_can_dp? ( country ) Phonelib . phone_data [ country ] && Phonelib . phone_data [ country ] [ Core :: DOUBLE_COUNTRY_PREFIX_FLAG ] && ! original_starts_with_plus? end
defines whether country can have double country prefix in number
2,433
def double_prefix_allowed? ( data , phone , parsed = { } ) data [ Core :: DOUBLE_COUNTRY_PREFIX_FLAG ] && phone =~ cr ( "^#{data[Core::COUNTRY_CODE]}" ) && parsed && ( parsed [ :valid ] . nil? || parsed [ :valid ] . empty? ) && ! original_starts_with_plus? end
checks if country can have numbers with double country prefixes
2,434
def country_or_default_country ( country ) country ||= ( original_starts_with_plus? ? nil : Phonelib . default_country ) country && country . to_s . upcase end
Get country that was provided or default country in needable format
2,435
def type_regex ( data , type ) regex = [ data [ type ] ] if Phonelib . parse_special && data [ Core :: SHORT ] && data [ Core :: SHORT ] [ type ] regex << data [ Core :: SHORT ] [ type ] end regex . join ( '|' ) end
Returns regex for type with special types if needed
2,436
def phone_match_data? ( phone , data , possible = false ) country_code = "#{data[Core::COUNTRY_CODE]}" inter_prefix = "(#{data[Core::INTERNATIONAL_PREFIX]})?" return unless phone . match cr ( "^0{2}?#{inter_prefix}#{country_code}" ) type = possible ? Core :: POSSIBLE_PATTERN : Core :: VALID_PATTERN phone . match full_regex_for_data ( data , type , false ) end
Check if phone match country data
2,437
def types_for_check ( data ) exclude_list = PhoneAnalyzer :: NOT_FOR_CHECK exclude_list += Phonelib :: Core :: SHORT_CODES unless Phonelib . parse_special Core :: TYPES_DESC . keys - exclude_list + fixed_and_mobile_keys ( data ) end
returns array of phone types for check for current country data
2,438
def fixed_and_mobile_keys ( data ) if data [ Core :: FIXED_LINE ] == data [ Core :: MOBILE ] [ Core :: FIXED_OR_MOBILE ] else [ Core :: FIXED_LINE , Core :: MOBILE ] end end
Checks if fixed line pattern and mobile pattern are the same and returns appropriate keys
2,439
def number_valid_and_possible? ( number , p_regex , v_regex , not_valid = false ) possible = number_match? ( number , p_regex ) return [ ! not_valid && possible , possible ] if p_regex == v_regex valid = ! not_valid && possible && number_match? ( number , v_regex ) [ valid && possible , possible ] end
Checks if passed number matches valid and possible patterns
2,440
def number_match? ( number , regex ) match = number . match ( cr ( "^(?:#{regex})$" ) ) match && match . to_s . length == number . length end
Checks number against regex and compares match length
2,441
def local_number return national unless possible? format_match , format_string = formatting_data if format_string =~ / \$ / && format_match format_string . gsub ( / \$ / , '$2' ) . gsub ( / \$ \d / ) { | el | format_match [ el [ 1 ] . to_i ] } else national end end
returns local number
2,442
def valid_for_country? ( country ) country = country . to_s . upcase tdata = analyze ( sanitized , passed_country ( country ) ) tdata . find do | iso2 , data | country == iso2 && data [ :valid ] . any? end . is_a? Array end
Returns whether a current parsed phone number is valid for specified country
2,443
def save_data_file File . open ( file_path ( Phonelib :: Core :: FILE_MAIN_DATA ) , 'wb+' ) do | f | Marshal . dump ( @data , f ) end end
method saves parsed data to data files
2,444
def save_extended_data_file extended = { Phonelib :: Core :: EXT_PREFIXES => @prefixes , Phonelib :: Core :: EXT_GEO_NAMES => @geo_names , Phonelib :: Core :: EXT_COUNTRY_NAMES => @countries , Phonelib :: Core :: EXT_TIMEZONES => @timezones , Phonelib :: Core :: EXT_CARRIERS => @carriers } File . open ( file_path ( Phonelib :: Core :: FILE_EXT_DATA ) , 'wb+' ) do | f | Marshal . dump ( extended , f ) end puts 'DATA SAVED' end
method saves extended data file
2,445
def fill_prefixes ( key , value , prefix , prefixes ) prefixes = { } if prefixes . nil? if prefix . size == 1 pr = prefix . to_i prefixes [ pr ] ||= { } prefixes [ pr ] [ key ] = value else pr = prefix [ 0 ] . to_i prefixes [ pr ] = fill_prefixes ( key , value , prefix [ 1 .. - 1 ] , prefixes [ pr ] ) end prefixes end
method updates prefixes hash recursively
2,446
def parse_raw_file ( file ) data = { } File . readlines ( file ) . each do | line | line = str_clean line , false next if line . empty? || line [ 0 ] == '#' prefix , line_data = line . split ( '|' ) data [ prefix ] = line_data && line_data . strip . split ( '&' ) end data end
method parses raw data file
2,447
def main_from_xml ( file ) xml_data = File . read ( file ) xml_data . force_encoding ( 'utf-8' ) doc = Nokogiri :: XML ( xml_data ) doc . elements . first . elements . first end
get main body from parsed xml document
2,448
def national ( formatted = true ) return @national_number unless valid? format_match , format_string = formatting_data if format_match out = format_string . gsub ( / \$ \d / ) { | el | format_match [ el [ 1 ] . to_i ] } formatted ? out : out . gsub ( / / , '' ) else @national_number end end
Returns formatted national number
2,449
def raw_national return nil if sanitized . nil? || sanitized . empty? if valid? @national_number elsif country_code && sanitized . start_with? ( country_code ) sanitized [ country_code . size .. - 1 ] else sanitized end end
Returns the raw national number that was defined during parsing
2,450
def international ( formatted = true , prefix = '+' ) prefix = formatted if formatted . is_a? ( String ) return nil if sanitized . empty? return "#{prefix}#{country_prefix_or_not}#{sanitized}" unless valid? return country_code + @national_number unless formatted fmt = @data [ country ] [ :format ] national = @national_number if ( matches = @national_number . match ( cr ( fmt [ Core :: PATTERN ] ) ) ) fmt = fmt [ :intl_format ] || fmt [ :format ] national = fmt . gsub ( / \$ \d / ) { | el | matches [ el [ 1 ] . to_i ] } unless fmt == 'NA' end "#{prefix}#{country_code} #{national}" end
Returns e164 formatted phone number . Method can receive single string parameter that will be defined as prefix
2,451
def area_code return nil unless area_code_possible? format_match , _format_string = formatting_data take_group = 1 if type == Core :: MOBILE && Core :: AREA_CODE_MOBILE_TOKENS [ country ] && format_match [ 1 ] == Core :: AREA_CODE_MOBILE_TOKENS [ country ] take_group = 2 end format_match [ take_group ] end
returns area code of parsed number
2,452
def tokenize string return nil if string . empty? return string if @string_cache . key? ( string ) return @symbol_cache [ string ] if @symbol_cache . key? ( string ) case string when / \d \. \s \$ \^ \* \( \) \{ \} \< \> \| \/ \\ / , / \n / if string . length > 5 @string_cache [ string ] = true return string end case string when / /i @string_cache [ string ] = true string when '~' , / /i nil when / /i true when / /i false else @string_cache [ string ] = true string end when TIME begin parse_time string rescue ArgumentError string end when / \d \d \d \d \d \d / require 'date' begin class_loader . date . strptime ( string , '%Y-%m-%d' ) rescue ArgumentError string end when / \. /i Float :: INFINITY when / \. /i - Float :: INFINITY when / \. /i Float :: NAN when / / if string =~ / \1 / @symbol_cache [ string ] = class_loader . symbolize ( $2 . sub ( / / , '' ) ) else @symbol_cache [ string ] = class_loader . symbolize ( string . sub ( / / , '' ) ) end when / / i = 0 string . split ( ':' ) . each_with_index do | n , e | i += ( n . to_i * 60 ** ( e - 2 ) . abs ) end i when / \. / i = 0 string . split ( ':' ) . each_with_index do | n , e | i += ( n . to_f * 60 ** ( e - 2 ) . abs ) end i when FLOAT if string =~ / \A \. \Z / @string_cache [ string ] = true string else Float ( string . gsub ( / \. / , '\1' ) ) end else int = parse_int string . gsub ( / / , '' ) return int if int @string_cache [ string ] = true string end end
Create a new scanner Tokenize + string + returning the Ruby object
2,453
def parse_time string klass = class_loader . load 'Time' date , time = * ( string . split ( / / , 2 ) ) ( yy , m , dd ) = date . match ( / \d \d \d / ) . captures . map { | x | x . to_i } md = time . match ( / \d \d \d \. \d \s \d \d \d / ) ( hh , mm , ss ) = md [ 1 ] . split ( ':' ) . map { | x | x . to_i } us = ( md [ 2 ] ? Rational ( "0.#{md[2]}" ) : 0 ) * 1000000 time = klass . utc ( yy , m , dd , hh , mm , ss , us ) return time if 'Z' == md [ 3 ] return klass . at ( time . to_i , us ) unless md [ 3 ] tz = md [ 3 ] . match ( / \- \d \: \d / ) [ 1 .. - 1 ] . compact . map { | digit | Integer ( digit , 10 ) } offset = tz . first * 3600 if offset < 0 offset -= ( ( tz [ 1 ] || 0 ) * 60 ) else offset += ( ( tz [ 1 ] || 0 ) * 60 ) end klass . new ( yy , m , dd , hh , mm , ss + us / ( 1_000_000 r ) , offset ) end
Parse and return a Time from + string +
2,454
def start_document version , tag_directives , implicit n = Nodes :: Document . new version , tag_directives , implicit set_start_location ( n ) @last . children << n push n end
Handles start_document events with + version + + tag_directives + and + implicit + styling .
2,455
def end_document implicit_end = ! streaming? @last . implicit_end = implicit_end n = pop set_end_location ( n ) n end
Handles end_document events with + version + + tag_directives + and + implicit + styling .
2,456
def delete_translation_values field_key = FieldKey . find_by_global_key ( params [ :i18n_key ] ) field_key . visible = false field_key . save! render json : { success : true } end
deletes the field_key referencing the translation
2,457
def create_for_locale field_key = FieldKey . find_by_global_key ( params [ :i18n_key ] ) phrase = I18n :: Backend :: ActiveRecord :: Translation . find_or_create_by ( key : field_key . global_key , locale : params [ :locale ] ) unless phrase . value . present? I18n . backend . reload! phrase . value = params [ :i18n_value ] phrase . save! end render json : { success : true } end
below for adding new locale to an existing translation
2,458
def buy @page = Pwb :: Page . find_by_slug "buy" @page_title = @current_agency . company_name if @page . present? @page_title = @page . page_title + ' - ' + @current_agency . company_name end @operation_type = "for_sale" @properties = Prop . visible . for_sale . limit 45 @prices_from_collection = @current_website . sale_price_options_from @prices_till_collection = @current_website . sale_price_options_till set_common_search_inputs set_select_picker_texts apply_search_filter filtering_params ( params ) set_map_markers @search_defaults = params [ :search ] . present? ? params [ :search ] : { } js 'Main/Search#sort' render "/pwb/search/buy" end
ordering of results happens client - side with paloma search . js
2,459
def set_features = ( features_json ) features_json . keys . each do | feature_key | if features_json [ feature_key ] == "true" || features_json [ feature_key ] == true features . find_or_create_by ( feature_key : feature_key ) else features . where ( feature_key : feature_key ) . delete_all end end end
Setter - called by update_extras in properties controller expects a hash with keys like cl . casafactory . fieldLabels . extras . alarma each with a value of true or false
2,460
def contextual_price_with_currency ( rent_or_sale ) contextual_price = self . contextual_price rent_or_sale if contextual_price . zero? return nil else return contextual_price . format ( no_cents : true ) end end
will return nil if price is 0
2,461
def update_photo content_tag = params [ :content_tag ] photo = ContentPhoto . find_by_id ( params [ :id ] ) unless photo if content_tag content = Content . find_by_key ( content_tag ) || Content . create ( { key : content_tag , tag : 'appearance' } ) photo = ContentPhoto . create if content_tag == "logo" content . content_photos . destroy_all end content . content_photos . push photo end end if params [ :file ] photo . image = params [ :file ] end photo . save! photo . reload render json : photo . to_json end
below is used by logo_photo and about_us_photo where only one photo is allowed
2,462
def create_content_with_photo tag = params [ :tag ] photo = ContentPhoto . create key = tag . underscore . camelize + photo . id . to_s new_content = Content . create ( tag : tag , key : key ) if params [ :file ] photo . image = params [ :file ] end photo . save! new_content . content_photos . push photo resource = Api :: V1 :: WebContentResource . new ( new_content , nil ) serializer = JSONAPI :: ResourceSerializer . new ( Api :: V1 :: WebContentResource ) photo . reload render json : serializer . serialize_to_hash ( resource ) end
below used when uploading carousel images
2,463
def seed_container_block_content ( locale , seed_content ) page_part_editor_setup = page_part . editor_setup raise "Invalid editorBlocks for page_part_editor_setup" unless page_part_editor_setup && page_part_editor_setup [ "editorBlocks" ] . present? locale_block_content_json = { "blocks" => { } } page_part_editor_setup [ "editorBlocks" ] . each do | configColBlocks | configColBlocks . each do | configRowBlock | row_block_label = configRowBlock [ "label" ] row_block_content = "" if seed_content [ row_block_label ] if configRowBlock [ "isImage" ] photo = seed_fragment_photo row_block_label , seed_content [ row_block_label ] if photo . present? && photo . optimized_image_url . present? row_block_content = photo . optimized_image_url else row_block_content = "http://via.placeholder.com/350x250" end else row_block_content = seed_content [ row_block_label ] end end locale_block_content_json [ "blocks" ] [ row_block_label ] = { "content" => row_block_content } end end update_page_part_content locale , locale_block_content_json p " #{page_part_key} content set for #{locale}." end
seed_content is ...
2,464
def set_page_part_block_contents ( _page_part_key , locale , fragment_details ) if page_part . present? page_part . block_contents [ locale ] = fragment_details page_part . save! fragment_details = page_part . block_contents [ locale ] end fragment_details end
set block contents on page_part model
2,465
def rebuild_page_content ( locale ) unless page_part && page_part . template raise "page_part with valid template not available" end if page_part . present? l_template = Liquid :: Template . parse ( page_part . template ) new_fragment_html = l_template . render ( 'page_part' => page_part . block_contents [ locale ] [ "blocks" ] ) page_fragment_content = find_or_create_content content_html_col = "raw_" + locale + "=" page_fragment_content . send content_html_col , new_fragment_html page_fragment_content . save! page_content_join_model = get_join_model page_content_join_model . page_part_key = page_part_key page_content_join_model . save! else new_fragment_html = "" end new_fragment_html end
Will retrieve saved page_part blocks and use that along with template to rebuild page_content html
2,466
def seed_fragment_photo ( block_label , photo_file ) page_fragment_content = find_or_create_content photo = page_fragment_content . content_photos . find_by_block_key ( block_label ) if photo . present? return photo else photo = page_fragment_content . content_photos . create ( block_key : block_label ) end if ENV [ "RAILS_ENV" ] == "test" return nil end begin photo . image = Pwb :: Engine . root . join ( photo_file ) . open photo . save! print "#{slug}--#{page_part_key} image created: #{photo.optimized_image_url}\n" photo . reload print "#{slug}--#{page_part_key} image created: #{photo.optimized_image_url}(after reload..)" rescue Exception => e print e end photo end
when seeding I only need to ensure that a photo exists for the fragment so will return existing photo if it can be found
2,467
def get_element_class ( element_name ) style_details = style_variables_for_theme [ "vic" ] || Pwb :: PresetStyle . default_values style_associations = style_details [ "associations" ] || [ ] style_associations [ element_name ] || "" end
spt 2017 - above 2 will be redundant once vic becomes default layout below used when rendering to decide which class names to use for which elements
2,468
def style_settings_from_preset = ( preset_style_name ) preset_style = Pwb :: PresetStyle . where ( name : preset_style_name ) . first if preset_style style_variables_for_theme [ "vic" ] = preset_style . attributes . as_json end end
allow setting of styles to a preset config from admin UI
2,469
def invoke_question ( object , message , * args , & block ) options = Utils . extract_options! ( args ) options [ :messages ] = self . class . messages question = object . new ( self , options ) question . ( message , & block ) end
Initialize a Prompt
2,470
def invoke_select ( object , question , * args , & block ) options = Utils . extract_options! ( args ) choices = if block [ ] elsif args . empty? possible = options . dup options = { } possible elsif args . size == 1 && args [ 0 ] . is_a? ( Hash ) Utils . extract_options! ( args ) else args . flatten end list = object . new ( self , options ) list . ( question , choices , & block ) end
Invoke a list type of prompt
2,471
def yes? ( message , * args , & block ) defaults = { default : true } options = Utils . extract_options! ( args ) options . merge! ( defaults . reject { | k , _ | options . key? ( k ) } ) question = ConfirmQuestion . new ( self , options ) question . call ( message , & block ) end
A shortcut method to ask the user positive question and return true for yes reply false for no .
2,472
def slider ( question , * args , & block ) options = Utils . extract_options! ( args ) slider = Slider . new ( self , options ) slider . call ( question , & block ) end
Ask a question with a range slider
2,473
def say ( message = '' , options = { } ) message = message . to_s return if message . empty? statement = Statement . new ( self , options ) statement . call ( message ) end
Print statement out . If the supplied message ends with a space or tab character a new line will not be appended .
2,474
def debug ( * messages ) longest = messages . max_by ( & :length ) . size width = TTY :: Screen . width - longest print cursor . save messages . each_with_index do | msg , i | print cursor . move_to ( width , i ) print cursor . clear_line_after print msg end print cursor . restore end
Print debug information in terminal top right corner
2,475
def suggest ( message , possibilities , options = { } ) suggestion = Suggestion . new ( options ) say ( suggestion . suggest ( message , possibilities ) ) end
Takes the string provided by the user and compare it with other possible matches to suggest an unambigous string
2,476
def collect ( options = { } , & block ) collector = AnswersCollector . new ( self , options ) collector . call ( & block ) end
Gathers more than one aswer
2,477
def extract_options ( args ) options = args . last options . respond_to? ( :to_hash ) ? options . to_hash . dup : { } end
Extract options hash from array argument
2,478
def blank? ( value ) value . nil? || value . respond_to? ( :empty? ) && value . empty? || BLANK_REGEX === value end
Check if value is nil or an empty string
2,479
def shush_backtraces Kernel . module_eval do old_raise = Kernel . method ( :raise ) remove_method :raise define_method :raise do | * args | begin old_raise . call ( * args ) ensure if $! lib = File . expand_path ( ".." , __FILE__ ) $! . backtrace . reject! { | line | line . start_with? ( lib ) } end end end private :raise end end
This feels very naughty
2,480
def decode ( s ) ts = lex ( s ) v , ts = textparse ( ts ) if ts . length > 0 raise Error , 'trailing garbage' end v end
Decodes a json document in string s and returns the corresponding ruby value . String s must be valid UTF - 8 . If you have a string in some other encoding convert it first .
2,481
def objparse ( ts ) ts = eat ( '{' , ts ) obj = { } if ts [ 0 ] [ 0 ] == '}' return obj , ts [ 1 .. - 1 ] end k , v , ts = pairparse ( ts ) obj [ k ] = v if ts [ 0 ] [ 0 ] == '}' return obj , ts [ 1 .. - 1 ] end loop do ts = eat ( ',' , ts ) k , v , ts = pairparse ( ts ) obj [ k ] = v if ts [ 0 ] [ 0 ] == '}' return obj , ts [ 1 .. - 1 ] end end end
Parses an object in the sense of RFC 4627 . Returns the parsed value and any trailing tokens .
2,482
def pairparse ( ts ) ( typ , _ , k ) , ts = ts [ 0 ] , ts [ 1 .. - 1 ] if typ != :str raise Error , "unexpected #{k.inspect}" end ts = eat ( ':' , ts ) v , ts = valparse ( ts ) [ k , v , ts ] end
Parses a member in the sense of RFC 4627 . Returns the parsed values and any trailing tokens .
2,483
def arrparse ( ts ) ts = eat ( '[' , ts ) arr = [ ] if ts [ 0 ] [ 0 ] == ']' return arr , ts [ 1 .. - 1 ] end v , ts = valparse ( ts ) arr << v if ts [ 0 ] [ 0 ] == ']' return arr , ts [ 1 .. - 1 ] end loop do ts = eat ( ',' , ts ) v , ts = valparse ( ts ) arr << v if ts [ 0 ] [ 0 ] == ']' return arr , ts [ 1 .. - 1 ] end end end
Parses an array in the sense of RFC 4627 . Returns the parsed value and any trailing tokens .
2,484
def tok ( s ) case s [ 0 ] when ?{ then [ '{' , s [ 0 , 1 ] , s [ 0 , 1 ] ] when ?} then [ '}' , s [ 0 , 1 ] , s [ 0 , 1 ] ] when ?: then [ ':' , s [ 0 , 1 ] , s [ 0 , 1 ] ] when ?, then [ ',' , s [ 0 , 1 ] , s [ 0 , 1 ] ] when ?[ then [ '[' , s [ 0 , 1 ] , s [ 0 , 1 ] ] when ?] then [ ']' , s [ 0 , 1 ] , s [ 0 , 1 ] ] when ?n then nulltok ( s ) when ?t then truetok ( s ) when ?f then falsetok ( s ) when ?" then strtok ( s ) when Spc , ?\t , ?\n , ?\r then [ :space , s [ 0 , 1 ] , s [ 0 , 1 ] ] else numtok ( s ) end end
Scans the first token in s and returns a 3 - element list or nil if s does not begin with a valid token .
2,485
def unquote ( q ) q = q [ 1 ... - 1 ] a = q . dup if rubydoesenc? a . force_encoding ( 'UTF-8' ) end r , w = 0 , 0 while r < q . length c = q [ r ] if c == ?\\ r += 1 if r >= q . length raise Error , "string literal ends with a \"\\\": \"#{q}\"" end case q [ r ] when ?" , ?\\ , ?/ , ?' a [ w ] = q [ r ] r += 1 w += 1 when ?b , ?f , ?n , ?r , ?t a [ w ] = Unesc [ q [ r ] ] r += 1 w += 1 when ?u r += 1 uchar = begin hexdec4 ( q [ r , 4 ] ) rescue RuntimeError => e raise Error , "invalid escape sequence \\u#{q[r,4]}: #{e}" end r += 4 if surrogate? uchar if q . length >= r + 6 uchar1 = hexdec4 ( q [ r + 2 , 4 ] ) uchar = subst ( uchar , uchar1 ) if uchar != Ucharerr r += 6 end end end if rubydoesenc? a [ w ] = '' << uchar w += 1 else w += ucharenc ( a , w , uchar ) end else raise Error , "invalid escape char #{q[r]} in \"#{q}\"" end elsif c == ?" || c < Spc raise Error , "invalid character in string literal \"#{q}\"" else a [ w ] = c r += 1 w += 1 end end a [ 0 , w ] end
Converts a quoted json string literal q into a UTF - 8 - encoded string . The rules are different than for Ruby so we cannot use eval . Unquote will raise an error if q contains control characters .
2,486
def ucharenc ( a , i , u ) if u <= Uchar1max a [ i ] = ( u & 0xff ) . chr 1 elsif u <= Uchar2max a [ i + 0 ] = ( Utag2 | ( ( u >> 6 ) & 0xff ) ) . chr a [ i + 1 ] = ( Utagx | ( u & Umaskx ) ) . chr 2 elsif u <= Uchar3max a [ i + 0 ] = ( Utag3 | ( ( u >> 12 ) & 0xff ) ) . chr a [ i + 1 ] = ( Utagx | ( ( u >> 6 ) & Umaskx ) ) . chr a [ i + 2 ] = ( Utagx | ( u & Umaskx ) ) . chr 3 else a [ i + 0 ] = ( Utag4 | ( ( u >> 18 ) & 0xff ) ) . chr a [ i + 1 ] = ( Utagx | ( ( u >> 12 ) & Umaskx ) ) . chr a [ i + 2 ] = ( Utagx | ( ( u >> 6 ) & Umaskx ) ) . chr a [ i + 3 ] = ( Utagx | ( u & Umaskx ) ) . chr 4 end end
Encodes unicode character u as UTF - 8 bytes in string a at position i . Returns the number of bytes written .
2,487
def run ( client ) with_child do child . send_io client child . gets or raise Errno :: EPIPE end pid = child . gets . to_i unless pid . zero? log "got worker pid #{pid}" pid end rescue Errno :: ECONNRESET , Errno :: EPIPE => e log "#{e} while reading from child; returning no pid" nil ensure client . close end
Returns the pid of the process running the command or nil if the application process died .
2,488
def symbolize_hash ( hash ) return hash unless hash . is_a? ( Hash ) hash . inject ( { } ) { | memo , ( key , value ) | memo [ key . to_sym ] = symbolize_hash ( value ) ; memo } end
Ensures that a hash uses symbols as opposed to strings Useful for allowing either syntax for end users
2,489
def single_content_for ( name , content = nil , & block ) @view_flow . set ( name , ActiveSupport :: SafeBuffer . new ) content_for ( name , content , & block ) end
Helper for setting content_for in activity partial needed to flush remains in between partial renders .
2,490
def create_activity! ( * args ) return unless self . public_activity_enabled? options = prepare_settings ( * args ) if call_hook_safe ( options [ :key ] . split ( '.' ) . last ) reset_activity_instance_options return PublicActivity :: Adapter . create_activity! ( self , options ) end end
Directly saves activity to database . Works the same as create_activity but throws validation error for each supported ORM .
2,491
def prepare_custom_fields ( options ) customs = self . class . activity_custom_fields_global . clone customs . merge! ( self . activity_custom_fields ) if self . activity_custom_fields customs . merge! ( options ) customs . each do | k , v | customs [ k ] = PublicActivity . resolve_value ( self , v ) end end
Prepares and resolves custom fields users can pass to tracked method
2,492
def prepare_key ( action , options = { } ) ( options [ :key ] || self . activity_key || ( ( self . class . name . underscore . gsub ( '/' , '_' ) + "." + action . to_s ) if action ) ) . try ( :to_s ) end
Helper method to serialize class name into relevant key
2,493
def text ( params = { } ) k = key . split ( '.' ) k . unshift ( 'activity' ) if k . first != 'activity' k = k . join ( '.' ) I18n . t ( k , parameters . merge ( params ) || { } ) end
Virtual attribute returning text description of the activity using the activity s key to translate using i18n .
2,494
def render ( context , params = { } ) partial_root = params . delete ( :root ) || 'public_activity' partial_path = nil layout_root = params . delete ( :layout_root ) || 'layouts' if params . has_key? :display if params [ :display ] . to_sym == :" " text = self . text ( params ) return context . render :text => text , :plain => text else partial_path = File . join ( partial_root , params [ :display ] . to_s ) end end context . render ( params . merge ( { :partial => prepare_partial ( partial_root , partial_path ) , :layout => prepare_layout ( layout_root , params . delete ( :layout ) ) , :locals => prepare_locals ( params ) } ) ) end
Renders activity from views .
2,495
def template_path ( key , partial_root ) path = key . split ( "." ) path . delete_at ( 0 ) if path [ 0 ] == "activity" path . unshift partial_root path . join ( "/" ) end
Builds the path to template based on activity key
2,496
def each @raw_page [ 'records' ] . each { | record | yield Restforce :: Mash . build ( record , @client ) } np = next_page while np np . current_page . each { | record | yield record } np = np . next_page end end
Given a hash and client will create an Enumerator that will lazily request Salesforce for the next page of results . Yield each value on each page .
2,497
def encode_www_form ( params ) if URI . respond_to? ( :encode_www_form ) URI . encode_www_form ( params ) else params . map do | k , v | k = CGI . escape ( k . to_s ) v = CGI . escape ( v . to_s ) "#{k}=#{v}" end . join ( '&' ) end end
Featured detect form encoding . URI in 1 . 8 does not include encode_www_form
2,498
def have_enum_values ( enum , values , headers = nil , & b ) values . each do | value | have_enum_value ( enum , value , headers , & b ) end end
Test for multiple values of the same enum type
2,499
def bgfill if @background_fill . nil? color = Magick :: Pixel . new ( 0 , 0 , 0 , Magick :: TransparentOpacity ) else color = @background_fill color . opacity = ( 1.0 - @background_fill_opacity ) * Magick :: TransparentOpacity end color end
background_fill defaults to none . If background_fill has been set to something else combine it with the background_fill_opacity .