idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
1,800
def deliver! ( mail ) envelope = Mail :: SmtpEnvelope . new ( mail ) response = smtp . sendmail ( dot_stuff ( envelope . message ) , envelope . from , envelope . to ) settings [ :return_response ] ? response : self end
Send the message via SMTP . The from and to attributes are optional . If not set they are retrieve from the Message .
1,801
def sanitize ( val ) val = val . gsub ( / \s \s / , '=' ) . gsub ( / / , '; ' ) . gsub ( / \s / , '' ) if val =~ / \S /i val = "#{$`.downcase}boundary=#{$2}#{$'.downcase}" else val . downcase! end case when val . chomp =~ / \s \w \- \/ \w \- \s \s \w \- /i "#{$1}/#{$2}; charset=#{Utilities.quote_atom($3)}" when val . chomp =~ / /i "text/plain;" when val . chomp =~ / \w \s /i "text/plain; #{$2}" when val =~ / \w \- \/ \w \- \s \w /i "#{$1}; charset=#{Utilities.quote_atom($2)}" when val =~ / \w \- \/ \w \- \s /i type = $1 params = $2 . to_s . split ( / \s / ) params = params . map { | i | i . to_s . chomp . strip } params = params . map { | i | i . split ( / \s \= \s / , 2 ) } params = params . map { | i | "#{i[0]}=#{Utilities.dquote(i[1].to_s.gsub(/;$/,""))}" } . join ( '; ' ) "#{type}; #{params}" when val =~ / \s / 'text/plain' else val end end
Various special cases from random emails found that I am not going to change the parser for
1,802
def quote_phrase ( str ) if str . respond_to? ( :force_encoding ) original_encoding = str . encoding ascii_str = str . to_s . dup . force_encoding ( 'ASCII-8BIT' ) if Constants :: PHRASE_UNSAFE === ascii_str dquote ( ascii_str ) . force_encoding ( original_encoding ) else str end else Constants :: PHRASE_UNSAFE === str ? dquote ( str ) : str end end
If the string supplied has PHRASE unsafe characters in it will return the string quoted in double quotes otherwise returns the string unmodified
1,803
def quote_token ( str ) if str . respond_to? ( :force_encoding ) original_encoding = str . encoding ascii_str = str . to_s . dup . force_encoding ( 'ASCII-8BIT' ) if token_safe? ( ascii_str ) str else dquote ( ascii_str ) . force_encoding ( original_encoding ) end else token_safe? ( str ) ? str : dquote ( str ) end end
If the string supplied has TOKEN unsafe characters in it will return the string quoted in double quotes otherwise returns the string unmodified
1,804
def capitalize_field ( str ) str . to_s . split ( "-" ) . map { | v | v . capitalize } . join ( "-" ) end
Capitalizes a string that is joined by hyphens correctly .
1,805
def constantize ( str ) str . to_s . split ( / / ) . map { | v | v . capitalize } . to_s end
Takes an underscored word and turns it into a class name
1,806
def blank? ( value ) if value . kind_of? ( NilClass ) true elsif value . kind_of? ( String ) value !~ / \S / else value . respond_to? ( :empty? ) ? value . empty? : ! value end end
Returns true if the object is considered blank . A blank includes things like nil and arrays and hashes that have nothing in them .
1,807
def find ( options = nil , & block ) options = validate_options ( options ) start do | imap | options [ :read_only ] ? imap . examine ( options [ :mailbox ] ) : imap . select ( options [ :mailbox ] ) uids = imap . uid_search ( options [ :keys ] , options [ :search_charset ] ) uids . reverse! if options [ :what ] . to_sym == :last uids = uids . first ( options [ :count ] ) if options [ :count ] . is_a? ( Integer ) uids . reverse! if ( options [ :what ] . to_sym == :last && options [ :order ] . to_sym == :asc ) || ( options [ :what ] . to_sym != :last && options [ :order ] . to_sym == :desc ) if block_given? uids . each do | uid | uid = options [ :uid ] . to_i unless options [ :uid ] . nil? fetchdata = imap . uid_fetch ( uid , [ 'RFC822' , 'FLAGS' ] ) [ 0 ] new_message = Mail . new ( fetchdata . attr [ 'RFC822' ] ) new_message . mark_for_delete = true if options [ :delete_after_find ] if block . arity == 4 yield new_message , imap , uid , fetchdata . attr [ 'FLAGS' ] elsif block . arity == 3 yield new_message , imap , uid else yield new_message end imap . uid_store ( uid , "+FLAGS" , [ Net :: IMAP :: DELETED ] ) if options [ :delete_after_find ] && new_message . is_marked_for_delete? break unless options [ :uid ] . nil? end imap . expunge if options [ :delete_after_find ] else emails = [ ] uids . each do | uid | uid = options [ :uid ] . to_i unless options [ :uid ] . nil? fetchdata = imap . uid_fetch ( uid , [ 'RFC822' ] ) [ 0 ] emails << Mail . new ( fetchdata . attr [ 'RFC822' ] ) imap . uid_store ( uid , "+FLAGS" , [ Net :: IMAP :: DELETED ] ) if options [ :delete_after_find ] break unless options [ :uid ] . nil? end imap . expunge if options [ :delete_after_find ] emails . size == 1 && options [ :count ] == 1 ? emails . first : emails end end end
Find emails in a IMAP mailbox . Without any options the 10 last received emails are returned .
1,808
def delete_all ( mailbox = 'INBOX' ) mailbox ||= 'INBOX' mailbox = Net :: IMAP . encode_utf7 ( mailbox ) start do | imap | imap . select ( mailbox ) imap . uid_search ( [ 'ALL' ] ) . each do | uid | imap . uid_store ( uid , "+FLAGS" , [ Net :: IMAP :: DELETED ] ) end imap . expunge end end
Delete all emails from a IMAP mailbox
1,809
def start ( config = Mail :: Configuration . instance , & block ) raise ArgumentError . new ( "Mail::Retrievable#imap_start takes a block" ) unless block_given? if settings [ :enable_starttls ] && settings [ :enable_ssl ] raise ArgumentError , ":enable_starttls and :enable_ssl are mutually exclusive. Set :enable_ssl if you're on an IMAPS connection. Set :enable_starttls if you're on an IMAP connection and using STARTTLS for secure TLS upgrade." end imap = Net :: IMAP . new ( settings [ :address ] , settings [ :port ] , settings [ :enable_ssl ] , nil , false ) imap . starttls if settings [ :enable_starttls ] if settings [ :authentication ] . nil? imap . login ( settings [ :user_name ] , settings [ :password ] ) else imap . authenticate ( settings [ :authentication ] , settings [ :user_name ] , settings [ :password ] ) end yield imap ensure if defined? ( imap ) && imap && ! imap . disconnected? imap . disconnect end end
Start an IMAP session and ensures that it will be closed in any case .
1,810
def fields = ( unfolded_fields ) @fields = Mail :: FieldList . new if unfolded_fields . size > self . class . maximum_amount Kernel . warn "WARNING: More than #{self.class.maximum_amount} header fields; only using the first #{self.class.maximum_amount} and ignoring the rest" unfolded_fields = unfolded_fields . slice ( 0 ... self . class . maximum_amount ) end unfolded_fields . each do | field | if field = Field . parse ( field , charset ) @fields . add_field field end end end
3 . 6 . Field definitions
1,811
def []= ( name , value ) name = name . to_s if name . include? ( Constants :: COLON ) raise ArgumentError , "Header names may not contain a colon: #{name.inspect}" end name = Utilities . dasherize ( name ) if value . nil? fields . delete_field name else fields . add_field Field . new ( name . to_s , value , charset ) if name == 'content-type' params = self [ :content_type ] . parameters rescue nil @charset = params [ :charset ] if params && params [ :charset ] end end end
Sets the FIRST matching field in the header to passed value or deletes the FIRST field matched from the header if passed nil
1,812
def default ( sym , val = nil ) if val header [ sym ] = val elsif field = header [ sym ] field . default end end
Returns the default value of the field requested as a symbol .
1,813
def []= ( name , value ) if name . to_s == 'body' self . body = value elsif name . to_s =~ / /i header [ name ] = value elsif name . to_s == 'charset' self . charset = value else header [ name ] = value end end
Allows you to add an arbitrary header
1,814
def method_missing ( name , * args , & block ) field_name = Utilities . underscoreize ( name ) . chomp ( "=" ) if Mail :: Field :: KNOWN_FIELDS . include? ( field_name ) if args . empty? header [ field_name ] else header [ field_name ] = args . first end else super end end
Method Missing in this implementation allows you to set any of the standard fields directly as you would the to subject etc .
1,815
def add_charset if ! body . empty? if @defaulted_charset && ! body . raw_source . ascii_only? && ! self . attachment? warning = "Non US-ASCII detected and no charset defined.\nDefaulting to UTF-8, set your own if this is incorrect.\n" warn ( warning ) end header [ :content_type ] . parameters [ 'charset' ] = @charset end end
Adds a content type and charset if the body is US - ASCII
1,816
def add_part ( part ) if ! body . multipart? && ! Utilities . blank? ( self . body . decoded ) @text_part = Mail :: Part . new ( 'Content-Type: text/plain;' ) @text_part . body = body . decoded self . body << @text_part add_multipart_alternate_header end add_boundary self . body << part end
Adds a part to the parts list or creates the part list
1,817
def part ( params = { } ) new_part = Part . new ( params ) yield new_part if block_given? add_part ( new_part ) end
Allows you to add a part in block form to an existing mail message object
1,818
def add_file ( values ) convert_to_multipart unless self . multipart? || Utilities . blank? ( self . body . decoded ) add_multipart_mixed_header if values . is_a? ( String ) basename = File . basename ( values ) filedata = File . open ( values , 'rb' ) { | f | f . read } else basename = values [ :filename ] filedata = values end self . attachments [ basename ] = filedata end
Adds a file to the message . You have two options with this method you can just pass in the absolute path to the file you want and Mail will read the file get the filename from the path you pass in and guess the MIME media type or you can pass in the filename as a string and pass in the file content as a blob .
1,819
def ready_to_send! identify_and_set_transfer_encoding parts . each do | part | part . transport_encoding = transport_encoding part . ready_to_send! end add_required_fields end
Encodes the message calls encode on all its parts gets an email message ready to send
1,820
def encoded ready_to_send! buffer = header . encoded buffer << "\r\n" buffer << body . encoded ( content_transfer_encoding ) buffer end
Outputs an encoded string representation of the mail message including all headers attachments etc . This is an encoded email in US - ASCII so it is able to be directly sent to an email server .
1,821
def body_lazy ( value ) process_body_raw if @body_raw && value case when value == nil || value . length <= 0 @body = Mail :: Body . new ( '' ) @body_raw = nil add_encoding_to_body when @body && @body . multipart? self . text_part = value else @body_raw = value end end
see comments to body = . We take data and process it lazily
1,822
def comments parse unless @parsed comments = get_comments if comments . nil? || comments . none? nil else comments . map { | c | c . squeeze ( Constants :: SPACE ) } end end
Returns an array of comments that are in the email or nil if there are no comments
1,823
def all ( options = nil , & block ) options = options ? Hash [ options ] : { } options [ :count ] = :all find ( options , & block ) end
Get all emails .
1,824
def find_and_delete ( options = nil , & block ) options = options ? Hash [ options ] : { } options [ :delete_after_find ] ||= true find ( options , & block ) end
Find emails in the mailbox and then deletes them . Without any options the five last received emails are returned .
1,825
def insert_field ( field ) lo , hi = 0 , size while lo < hi mid = ( lo + hi ) . div ( 2 ) if field < self [ mid ] hi = mid else lo = mid + 1 end end insert lo , field end
Insert the field in sorted order .
1,826
def update_all_catalogs_and_return_filepaths does_rambafile_exist = Dir [ RAMBAFILE_NAME ] . count > 0 if does_rambafile_exist rambafile = YAML . load_file ( RAMBAFILE_NAME ) catalogs = rambafile [ CATALOGS_KEY ] end terminator = CatalogTerminator . new terminator . remove_all_catalogs catalog_paths = [ download_catalog ( GENERAMBA_CATALOG_NAME , RAMBLER_CATALOG_REPO ) ] if catalogs != nil && catalogs . count > 0 catalogs . each do | catalog_url | catalog_name = catalog_url . split ( '://' ) . last catalog_name = catalog_name . gsub ( '/' , '-' ) ; catalog_paths . push ( download_catalog ( catalog_name , catalog_url ) ) end end return catalog_paths end
Updates all of the template catalogs and returns their filepaths . If there is a Rambafile in the current directory it also updates all of the catalogs specified there .
1,827
def download_catalog ( name , url ) catalogs_local_path = Pathname . new ( ENV [ 'HOME' ] ) . join ( GENERAMBA_HOME_DIR ) . join ( CATALOGS_DIR ) current_catalog_path = catalogs_local_path . join ( name ) if File . exists? ( current_catalog_path ) g = Git . open ( current_catalog_path ) g . pull else Git . clone ( url , name , :path => catalogs_local_path ) end return current_catalog_path end
Clones a template catalog from a remote repository
1,828
def installer_for_type ( type ) case type when TemplateDeclarationType :: LOCAL_TEMPLATE return Generamba :: LocalInstaller . new when TemplateDeclarationType :: REMOTE_TEMPLATE return Generamba :: RemoteInstaller . new when TemplateDeclarationType :: CATALOG_TEMPLATE return Generamba :: CatalogInstaller . new else return nil end end
Provides the appropriate strategy for a given template type
1,829
def browse_catalog_for_a_template ( catalog_path , template_name ) template_path = catalog_path . join ( template_name ) if Dir . exist? ( template_path ) return template_path end return nil end
Browses a given catalog and returns a template path
1,830
def install_templates ( rambafile ) clear_installed_templates templates = rambafile [ TEMPLATES_KEY ] if ! templates || templates . count == 0 puts 'You must specify at least one template in Rambafile under the key *templates*' . red return end templates = rambafile [ TEMPLATES_KEY ] . map { | template_hash | Generamba :: TemplateDeclaration . new ( template_hash ) } catalogs = rambafile [ CATALOGS_KEY ] update_catalogs_if_needed ( catalogs , templates ) templates . each do | template_declaration | strategy = @installer_factory . installer_for_type ( template_declaration . type ) template_declaration . install ( strategy ) end end
This method parses Rambafile serializes templates hashes into model objects and install them
1,831
def clear_installed_templates install_path = Pathname . new ( TEMPLATES_FOLDER ) FileUtils . rm_rf ( Dir . glob ( install_path ) ) end
Clears all of the currently installed templates
1,832
def update_catalogs_if_needed ( catalogs , templates ) needs_update = templates . any? { | template | template . type == TemplateDeclarationType :: CATALOG_TEMPLATE } return unless needs_update terminator = CatalogTerminator . new terminator . remove_all_catalogs puts ( 'Updating shared generamba-catalog specs...' ) @catalog_downloader . download_catalog ( GENERAMBA_CATALOG_NAME , RAMBLER_CATALOG_REPO ) return unless catalogs != nil && catalogs . count > 0 catalogs . each do | catalog_url | catalog_name = catalog_url . split ( '://' ) . last catalog_name = catalog_name . gsub ( '/' , '-' ) ; puts ( "Updating #{catalog_name} specs..." ) @catalog_downloader . download_catalog ( catalog_name , catalog_url ) end end
Clones remote template catalogs to the local directory
1,833
def configure_with_targets ( runnable_target , test_target , launch_target : false ) if runnable_target add_build_target ( runnable_target ) set_launch_target ( runnable_target ) if launch_target end if test_target add_build_target ( test_target , false ) if test_target != runnable_target add_test_target ( test_target ) end end
Create a XCScheme either from scratch or using an existing file
1,834
def set_launch_target ( build_target ) launch_runnable = BuildableProductRunnable . new ( build_target , 0 ) launch_action . buildable_product_runnable = launch_runnable profile_runnable = BuildableProductRunnable . new ( build_target ) profile_action . buildable_product_runnable = profile_runnable macro_exp = MacroExpansion . new ( build_target ) test_action . add_macro_expansion ( macro_exp ) end
Sets a runnable target to be the target of the launch action of the scheme .
1,835
def save_as ( project_path , name , shared = true ) scheme_folder_path = if shared self . class . shared_data_dir ( project_path ) else self . class . user_data_dir ( project_path ) end scheme_folder_path . mkpath scheme_path = scheme_folder_path + "#{name}.xcscheme" @file_path = scheme_path File . open ( scheme_path , 'w' ) do | f | f . write ( to_s ) end end
Serializes the current state of the object to a . xcscheme file .
1,836
def initialize_from_file pbxproj_path = path + 'project.pbxproj' plist = Plist . read_from_path ( pbxproj_path . to_s ) root_object . remove_referrer ( self ) if root_object @root_object = new_from_plist ( plist [ 'rootObject' ] , plist [ 'objects' ] , self ) @archive_version = plist [ 'archiveVersion' ] @object_version = plist [ 'objectVersion' ] @classes = plist [ 'classes' ] || { } @dirty = false unless root_object raise "[Xcodeproj] Unable to find a root object in #{pbxproj_path}." end if archive_version . to_i > Constants :: LAST_KNOWN_ARCHIVE_VERSION raise '[Xcodeproj] Unknown archive version.' end if object_version . to_i > Constants :: LAST_KNOWN_OBJECT_VERSION raise '[Xcodeproj] Unknown object version.' end root_object . product_ref_group ||= root_object . main_group [ 'Products' ] || root_object . main_group . new_group ( 'Products' ) end
Initializes the instance with the project stored in the path attribute .
1,837
def to_tree_hash hash = { } objects_dictionary = { } hash [ 'objects' ] = objects_dictionary hash [ 'archiveVersion' ] = archive_version . to_s hash [ 'objectVersion' ] = object_version . to_s hash [ 'classes' ] = classes hash [ 'rootObject' ] = root_object . to_tree_hash hash end
Converts the objects tree to a hash substituting the hash of the referenced to their UUID reference . As a consequence the hash of an object might appear multiple times and the information about their uniqueness is lost .
1,838
def generate_available_uuid_list ( count = 100 ) new_uuids = ( 0 .. count ) . map { SecureRandom . hex ( 12 ) . upcase } uniques = ( new_uuids - ( @generated_uuids + uuids ) ) @generated_uuids += uniques @available_uuids += uniques end
Pre - generates the given number of UUIDs . Useful for optimizing performance when the rough number of objects that will be created is known in advance .
1,839
def reference_for_path ( absolute_path ) absolute_pathname = Pathname . new ( absolute_path ) unless absolute_pathname . absolute? raise ArgumentError , "Paths must be absolute #{absolute_path}" end objects . find do | child | child . isa == 'PBXFileReference' && child . real_path == absolute_pathname end end
Returns the file reference for the given absolute path .
1,840
def embedded_targets_in_native_target ( native_target ) native_targets . select do | target | host_targets_for_embedded_target ( target ) . map ( & :uuid ) . include? native_target . uuid end end
Checks the native target for any targets in the project that are dependent on the native target and would be embedded in it at build time
1,841
def host_targets_for_embedded_target ( embedded_target ) native_targets . select do | native_target | ( ( embedded_target . uuid != native_target . uuid ) && ( native_target . dependencies . map ( & :native_target_uuid ) . include? embedded_target . uuid ) ) end end
Returns the native targets in which the embedded target is embedded . This works by traversing the targets to find those where the target is a dependency .
1,842
def new_resources_bundle ( name , platform , product_group = nil ) product_group ||= products_group ProjectHelper . new_resources_bundle ( self , name , platform , product_group ) end
Creates a new resource bundles target and adds it to the project .
1,843
def add_build_configuration ( name , type ) build_configuration_list = root_object . build_configuration_list if build_configuration = build_configuration_list [ name ] build_configuration else build_configuration = new ( XCBuildConfiguration ) build_configuration . name = name common_settings = Constants :: PROJECT_DEFAULT_BUILD_SETTINGS settings = ProjectHelper . deep_dup ( common_settings [ :all ] ) settings . merge! ( ProjectHelper . deep_dup ( common_settings [ type ] ) ) build_configuration . build_settings = settings build_configuration_list . build_configurations << build_configuration build_configuration end end
Adds a new build configuration to the project and populates its with default settings according to the provided type .
1,844
def save_as ( pathname , prefix = nil ) if File . exist? ( pathname ) return if Config . new ( pathname ) == self end pathname . open ( 'w' ) { | file | file << to_s ( prefix ) } end
Writes the serialized representation of the internal data to the given path .
1,845
def hash_from_file_content ( string ) hash = { } string . split ( "\n" ) . each do | line | uncommented_line = strip_comment ( line ) if include = extract_include ( uncommented_line ) @includes . push normalized_xcconfig_path ( include ) else key , value = extract_key_value ( uncommented_line ) next unless key value . gsub! ( INHERITED_REGEXP ) { | m | hash . fetch ( key , m ) } hash [ key ] = value end end hash end
Returns a hash from the string representation of an Xcconfig file .
1,846
def merge_attributes! ( attributes ) @attributes . merge! ( attributes ) do | _ , v1 , v2 | v1 = v1 . strip v2 = v2 . strip v1_split = v1 . shellsplit v2_split = v2 . shellsplit if ( v2_split - v1_split ) . empty? || v1_split . first ( v2_split . size ) == v2_split v1 elsif v2_split . first ( v1_split . size ) == v1_split v2 else "#{v1} #{v2}" end end end
Merges the given attributes hash while ensuring values are not duplicated .
1,847
def extract_key_value ( line ) match = line . match ( KEY_VALUE_PATTERN ) if match key = match [ 1 ] value = match [ 2 ] [ key . strip , value . strip ] else [ ] end end
Returns the key and the value described by the given line of an xcconfig .
1,848
def compare_settings ( produced , expected , params ) it 'should match build settings' do missing_settings = expected . keys . reject { | k | produced . key? ( k ) } unexpected_settings = produced . keys . reject { | k | expected . key? ( k ) } wrong_settings = ( expected . keys - missing_settings ) . select do | k | produced_setting = produced [ k ] produced_setting = produced_setting . join ( ' ' ) if produced_setting . respond_to? :join produced_setting != expected [ k ] end description = [ ] description << "Doesn't match build settings for \e[1m#{params}\e[0m" if wrong_settings . count > 0 description << 'Wrong build settings:' description += wrong_settings . map { | s | "* #{s.to_s.yellow} is #{produced[s].to_s.red}, but should be #{expected[s].to_s.green}" } description << '' end if missing_settings . count > 0 description << 'Missing build settings:' description << missing_settings . map { | s | "* #{s.to_s.red} (#{expected[s]})" } description << '' end if unexpected_settings . count > 0 description << 'Unexpected additional build settings:' description += unexpected_settings . map { | s | "* #{s.to_s.green} (#{produced[s]})" } description << '' end faulty_settings = missing_settings + unexpected_settings + wrong_settings faulty_settings . should . satisfy ( description * "\n" ) do faulty_settings . length == 0 end end end
Generates test cases to compare two settings hashes .
1,849
def load_settings ( path , type ) base_path = Pathname ( fixture_path ( "CommonBuildSettings/configs/#{path}" ) ) config_fixture = base_path + "#{path}_#{type}.xcconfig" config = Xcodeproj :: Config . new ( config_fixture ) settings = config . to_hash settings = apply_exclusions ( settings , EXCLUDED_KEYS ) project_defaults_by_config = Xcodeproj :: Constants :: PROJECT_DEFAULT_BUILD_SETTINGS project_defaults = project_defaults_by_config [ :all ] project_defaults . merge ( project_defaults_by_config [ type ] ) unless type == :base settings = apply_exclusions ( settings , project_defaults ) settings end
Load settings from fixtures
1,850
def save_as ( path ) FileUtils . mkdir_p ( path ) File . open ( File . join ( path , 'contents.xcworkspacedata' ) , 'w' ) do | out | out << to_s end end
Saves the workspace at the given xcworkspace path .
1,851
def load_schemes_from_project ( project_full_path ) schemes = Xcodeproj :: Project . schemes project_full_path schemes . each do | scheme_name | @schemes [ scheme_name ] = project_full_path end end
Load all schemes from project
1,852
def container @opf_path = opf_path tmplfile = File . expand_path ( './xml/container.xml.erb' , ReVIEW :: Template :: TEMPLATE_DIR ) tmpl = ReVIEW :: Template . load ( tmplfile ) tmpl . result ( binding ) end
Return container content .
1,853
def mytoc @title = CGI . escapeHTML ( @producer . res . v ( 'toctitle' ) ) @body = %Q( <h1 class="toc-title">#{CGI.escapeHTML(@producer.res.v('toctitle'))}</h1>\n) if @producer . config [ 'epubmaker' ] [ 'flattoc' ] . nil? @body << hierarchy_ncx ( 'ul' ) else @body << flat_ncx ( 'ul' , @producer . config [ 'epubmaker' ] [ 'flattocindent' ] ) end @language = @producer . config [ 'language' ] @stylesheets = @producer . config [ 'stylesheet' ] tmplfile = if @producer . config [ 'htmlversion' ] . to_i == 5 File . expand_path ( './html/layout-html5.html.erb' , ReVIEW :: Template :: TEMPLATE_DIR ) else File . expand_path ( './html/layout-xhtml1.html.erb' , ReVIEW :: Template :: TEMPLATE_DIR ) end tmpl = ReVIEW :: Template . load ( tmplfile ) tmpl . result ( binding ) end
Return own toc content .
1,854
def compile_inline ( str ) op , arg = / \A \w \{ \} \z / . match ( str ) . captures unless inline_defined? ( op ) raise CompileError , "no such inline op: #{op}" end unless @strategy . respond_to? ( "inline_#{op}" ) raise "strategy does not support inline op: @<#{op}>" end @strategy . __send__ ( "inline_#{op}" , arg ) rescue => e error e . message @strategy . nofunc_text ( str ) end
called from strategy
1,855
def load ( file ) if file . nil? || ! File . exist? ( file ) raise "Can't open #{file}." end loader = ReVIEW :: YAMLLoader . new merge_config ( @config . deep_merge ( loader . load_file ( file ) ) ) end
Take YAML + file + and update parameter hash .
1,856
def merge_config ( config ) @config . deep_merge! ( config ) complement unless @config [ 'epubversion' ] . nil? case @config [ 'epubversion' ] . to_i when 2 @epub = EPUBMaker :: EPUBv2 . new ( self ) when 3 @epub = EPUBMaker :: EPUBv3 . new ( self ) else raise "Invalid EPUB version (#{@config['epubversion']}.)" end end if config [ 'language' ] ReVIEW :: I18n . locale = config [ 'language' ] end support_legacy_maker end
Update parameters by merging from new parameter hash + config + .
1,857
def mimetype ( wobj ) s = @epub . mimetype if ! s . nil? && ! wobj . nil? wobj . print s end end
Write mimetype file to IO object + wobj + .
1,858
def opf ( wobj ) s = @epub . opf if ! s . nil? && ! wobj . nil? wobj . puts s end end
Write opf file to IO object + wobj + .
1,859
def ncx ( wobj , indentarray = [ ] ) s = @epub . ncx ( indentarray ) if ! s . nil? && ! wobj . nil? wobj . puts s end end
Write ncx file to IO object + wobj + . + indentarray + defines prefix string for each level .
1,860
def container ( wobj ) s = @epub . container if ! s . nil? && ! wobj . nil? wobj . puts s end end
Write container file to IO object + wobj + .
1,861
def colophon ( wobj ) s = @epub . colophon if ! s . nil? && ! wobj . nil? wobj . puts s end end
Write colophon file to IO object + wobj + .
1,862
def mytoc ( wobj ) s = @epub . mytoc if ! s . nil? && ! wobj . nil? wobj . puts s end end
Write own toc file to IO object + wobj + .
1,863
def ncx ( indentarray ) @ncx_isbn = ncx_isbn @ncx_doctitle = ncx_doctitle @ncx_navmap = ncx_navmap ( indentarray ) tmplfile = File . expand_path ( './ncx/epubv2.ncx.erb' , ReVIEW :: Template :: TEMPLATE_DIR ) ReVIEW :: Template . load ( tmplfile ) . result ( binding ) end
Return ncx content . + indentarray + has prefix marks for each level .
1,864
def produce ( epubfile , basedir , tmpdir ) produce_write_common ( basedir , tmpdir ) File . open ( "#{tmpdir}/OEBPS/#{@producer.config['bookname']}.ncx" , 'w' ) do | f | @producer . ncx ( f , @producer . config [ 'epubmaker' ] [ 'ncxindent' ] ) end if @producer . config [ 'mytoc' ] File . open ( "#{tmpdir}/OEBPS/#{@producer.config['bookname']}-toc.#{@producer.config['htmlext']}" , 'w' ) do | f | @producer . mytoc ( f ) end end @producer . call_hook ( @producer . config [ 'epubmaker' ] [ 'hook_prepack' ] , tmpdir ) expoter = EPUBMaker :: ZipExporter . new ( tmpdir , @producer . config ) expoter . export_zip ( epubfile ) end
Produce EPUB file + epubfile + . + basedir + points the directory has contents . + tmpdir + defines temporary directory .
1,865
def inline_i ( str ) if @book . config . check_version ( '2' , exception : false ) macro ( 'textit' , escape ( str ) ) else macro ( 'reviewit' , escape ( str ) ) end end
index - > italic
1,866
def load_file ( yamlfile ) file_queue = [ File . expand_path ( yamlfile ) ] loaded_files = { } yaml = { } loop do return yaml if file_queue . empty? current_file = file_queue . shift current_yaml = YAML . load_file ( current_file ) yaml = current_yaml . deep_merge ( yaml ) next unless yaml . key? ( 'inherit' ) buf = [ ] yaml [ 'inherit' ] . reverse_each do | item | inherit_file = File . expand_path ( item , File . dirname ( yamlfile ) ) if loaded_files [ inherit_file ] raise "Found circular YAML inheritance '#{inherit_file}' in #{yamlfile}." end loaded_files [ inherit_file ] = true buf << inherit_file end yaml . delete ( 'inherit' ) file_queue = buf + file_queue end end
load YAML files
1,867
def complement if @id . nil? @id = @file . gsub ( %r{ \\ \. } , '-' ) end if @id =~ / \A /i @id = "rv-#{@id}" end if ! @file . nil? && @media . nil? @media = @file . sub ( / \. / , '' ) . downcase end case @media when 'xhtml' , 'xml' , 'html' @media = 'application/xhtml+xml' when 'css' @media = 'text/css' when 'jpg' , 'jpeg' , 'image/jpg' @media = 'image/jpeg' when 'png' @media = 'image/png' when 'gif' @media = 'image/gif' when 'svg' , 'image/svg' @media = 'image/svg+xml' when 'ttf' , 'otf' @media = 'application/vnd.ms-opentype' when 'woff' @media = 'application/font-woff' end if @id . nil? || @file . nil? || @media . nil? raise "Type error: #{id}, #{file}, #{media}, #{title}, #{notoc}" end end
Complement other parameters by using file parameter .
1,868
def choose! ( context = nil ) @user . cleanup_old_experiments! return alternative if @alternative_choosen if override_is_alternative? self . alternative = @options [ :override ] if should_store_alternative? && ! @user [ @experiment . key ] self . alternative . increment_participation end elsif @options [ :disabled ] || Split . configuration . disabled? self . alternative = @experiment . control elsif @experiment . has_winner? self . alternative = @experiment . winner else cleanup_old_versions if exclude_user? self . alternative = @experiment . control else self . alternative = @user [ @experiment . key ] if alternative . nil? self . alternative = @experiment . next_alternative self . alternative . increment_participation run_callback context , Split . configuration . on_trial_choose end end end @user [ @experiment . key ] = alternative . name if ! @experiment . has_winner? && should_store_alternative? @alternative_choosen = true run_callback context , Split . configuration . on_trial unless @options [ :disabled ] || Split . configuration . disabled? alternative end
Choose an alternative add a participant and save the alternative choice on the user . This method is guaranteed to only run once and will skip the alternative choosing process if run a second time .
1,869
def parse_connect_attrs ( conn_attrs ) return { } if Mysql2 :: Client :: CONNECT_ATTRS . zero? conn_attrs ||= { } conn_attrs [ :program_name ] ||= $PROGRAM_NAME conn_attrs . each_with_object ( { } ) do | ( key , value ) , hash | hash [ key . to_s ] = value . to_s end end
Set default program_name in performance_schema . session_connect_attrs and performance_schema . session_account_connect_attrs
1,870
def clean_message ( message ) if @server_version && @server_version > 50500 message . encode ( ENCODE_OPTS ) else message . encode ( Encoding :: UTF_8 , ENCODE_OPTS ) end end
In MySQL 5 . 5 + error messages are always constructed server - side as UTF - 8 then returned in the encoding set by the character_set_results system variable .
1,871
def resource ( * args , & block ) options = args . last . is_a? ( Hash ) ? args . pop : { } options [ :api_doc_dsl ] = :resource options [ :resource_name ] = args . first . to_s options [ :document ] = :all unless options . key? ( :document ) args . push ( options ) describe ( * args , & block ) end
Custom describe block that sets metadata to enable the rest of RAD
1,872
def define_group ( name , & block ) subconfig = self . class . new ( self ) subconfig . filter = name subconfig . docs_dir = self . docs_dir . join ( name . to_s ) yield subconfig groups << subconfig end
Defines a new sub configuration
1,873
def lines_to_display ( full_trace ) ActiveRecordQueryTrace . lines . zero? ? full_trace : full_trace . first ( ActiveRecordQueryTrace . lines ) end
Must be called after the backtrace cleaner .
1,874
def setup_backtrace_cleaner_path return unless Rails . backtrace_cleaner . instance_variable_get ( :@root ) == '/' Rails . backtrace_cleaner . instance_variable_set :@root , Rails . root . to_s end
Rails relies on backtrace cleaner to set the application root directory filter . The problem is that the backtrace cleaner is initialized before this gem . This ensures that the value of root used by the filter is correct .
1,875
def update_attributes ( values , opts = { } , dirty : true ) values . each do | k , v | add_accessors ( [ k ] , values ) unless metaclass . method_defined? ( k . to_sym ) @values [ k ] = Util . convert_to_stripe_object ( v , opts ) dirty_value! ( @values [ k ] ) if dirty @unsaved_values . add ( k ) end end
Mass assigns attributes on the model .
1,876
def empty_values ( obj ) values = case obj when Hash then obj when StripeObject then obj . instance_variable_get ( :@values ) else raise ArgumentError , "#empty_values got unexpected object type: #{obj.class.name}" end values . each_with_object ( { } ) do | ( k , _ ) , update | update [ k ] = "" end end
Returns a hash of empty values for all the values that are in the given StripeObject .
1,877
def auto_paging_each ( & blk ) return enum_for ( :auto_paging_each ) unless block_given? page = self loop do page . each ( & blk ) page = page . next_page break if page . empty? end end
Iterates through each resource in all pages making additional fetches to the API as necessary .
1,878
def format_app_info ( info ) str = info [ :name ] str = "#{str}/#{info[:version]}" unless info [ :version ] . nil? str = "#{str} (#{info[:url]})" unless info [ :url ] . nil? str end
Formats a plugin app info hash into a string that we can tack onto the end of a User - Agent string where it ll be fairly prominent in places like the Dashboard . Note that this formatting has been implemented to match other libraries and shouldn t be changed without universal consensus .
1,879
def specific_oauth_error ( resp , error_code , context ) description = resp . data [ :error_description ] || error_code Util . log_error ( "Stripe OAuth error" , status : resp . http_status , error_code : error_code , error_description : description , idempotency_key : context . idempotency_key , request_id : context . request_id ) args = [ error_code , description , { http_status : resp . http_status , http_body : resp . http_body , json_body : resp . data , http_headers : resp . http_headers , } , ] case error_code when "invalid_client" then OAuth :: InvalidClientError . new ( * args ) when "invalid_grant" then OAuth :: InvalidGrantError . new ( * args ) when "invalid_request" then OAuth :: InvalidRequestError . new ( * args ) when "invalid_scope" then OAuth :: InvalidScopeError . new ( * args ) when "unsupported_grant_type" then OAuth :: UnsupportedGrantTypeError . new ( * args ) when "unsupported_response_type" then OAuth :: UnsupportedResponseTypeError . new ( * args ) else OAuth :: OAuthError . new ( * args ) end end
Attempts to look at a response s error code and return an OAuth error if one matches . Will return nil if the code isn t recognized .
1,880
def awesome_active_record_instance ( object ) return object . inspect if ! defined? ( :: ActiveSupport :: OrderedHash ) return awesome_object ( object ) if @options [ :raw ] data = if object . class . column_names != object . attributes . keys object . attributes else object . class . column_names . inject ( :: ActiveSupport :: OrderedHash . new ) do | hash , name | if object . has_attribute? ( name ) || object . new_record? value = object . respond_to? ( name ) ? object . send ( name ) : object . read_attribute ( name ) hash [ name . to_sym ] = value end hash end end "#{object} " << awesome_hash ( data ) end
Format ActiveRecord instance object .
1,881
def awesome_ripple_document_instance ( object ) return object . inspect if ! defined? ( :: ActiveSupport :: OrderedHash ) return awesome_object ( object ) if @options [ :raw ] exclude_assoc = @options [ :exclude_assoc ] or @options [ :exclude_associations ] data = object . attributes . inject ( :: ActiveSupport :: OrderedHash . new ) do | hash , ( name , value ) | hash [ name . to_sym ] = object . send ( name ) hash end unless exclude_assoc data = object . class . embedded_associations . inject ( data ) do | hash , assoc | hash [ assoc . name ] = object . get_proxy ( assoc ) hash end end "#{object} " << awesome_hash ( data ) end
Format Ripple instance object .
1,882
def awesome_mongo_mapper_instance ( object ) return object . inspect if ! defined? ( :: ActiveSupport :: OrderedHash ) return awesome_object ( object ) if @options [ :raw ] data = object . keys . keys . sort_by { | k | k } . inject ( :: ActiveSupport :: OrderedHash . new ) do | hash , name | hash [ name ] = object [ name ] hash end if @options [ :mongo_mapper ] [ :show_associations ] object . associations . each do | name , assoc | data [ name . to_s ] = if @options [ :mongo_mapper ] [ :inline_embedded ] and assoc . embeddable? object . send ( name ) else assoc end end end label = object . to_s label = "#{colorize('embedded', :assoc)} #{label}" if object . is_a? ( :: MongoMapper :: EmbeddedDocument ) "#{label} " << awesome_hash ( data ) end
Format MongoMapper instance object .
1,883
def ap_debug ( object , options = { } ) object . ai ( options . merge ( html : true ) ) . sub ( / \s / , '<pre class="debug_dump"\\1' ) end
Use HTML colors and add default debug_dump class to the resulting HTML .
1,884
def ancestors node = self nodes = [ ] nodes << node = node . parent while node . parent nodes end
Returns list of ancestors starting from parent until root .
1,885
def descendants nodes = [ ] children . each do | c | nodes << c nodes << c . descendants end nodes . flatten end
Returns all children and children of children
1,886
def export! ( classes = nil ) classes ||= SEED_CLASSES classes . each do | klass | klass = "ComfortableMexicanSofa::Seeds::#{klass}::Exporter" klass . constantize . new ( from , to ) . export! end end
if passed nil will use default seed classes
1,887
def write_file_content ( path , data ) :: File . open ( :: File . join ( path ) , "wb" ) do | f | data . each do | item | f . write ( "[#{item[:header]}]\n" ) f . write ( "#{item[:content]}\n" ) end end end
Writing to the seed file . Takes in file handler and array of hashes with header and content keys
1,888
def fragments_data ( record , page_path ) record . fragments . collect do | frag | header = "#{frag.tag} #{frag.identifier}" content = case frag . tag when "datetime" , "date" frag . datetime when "checkbox" frag . boolean when "file" , "files" frag . attachments . map do | attachment | :: File . open ( :: File . join ( page_path , attachment . filename . to_s ) , "wb" ) do | f | f . write ( attachment . download ) end attachment . filename end . join ( "\n" ) else frag . content end { header : header , content : content } end end
Collecting fragment data and writing attachment files to disk
1,889
def import_translations ( path , page ) old_translations = page . translations . pluck ( :locale ) new_translations = [ ] Dir [ "#{path}content.*.html" ] . each do | file_path | locale = File . basename ( file_path ) . match ( %r{ \. \w \. } ) [ 1 ] new_translations << locale translation = page . translations . where ( locale : locale ) . first_or_initialize next unless fresh_seed? ( translation , file_path ) fragments_hash = parse_file_content ( file_path ) attributes_yaml = fragments_hash . delete ( "attributes" ) attrs = YAML . safe_load ( attributes_yaml ) layout = site . layouts . find_by ( identifier : attrs . delete ( "layout" ) ) || page . try ( :layout ) translation . attributes = attrs . merge ( layout : layout ) old_frag_identifiers = translation . fragments . pluck ( :identifier ) new_frag_identifiers , fragments_attributes = construct_fragments_attributes ( fragments_hash , translation , path ) translation . fragments_attributes = fragments_attributes if translation . save message = "[CMS SEEDS] Imported Translation \t #{locale}" ComfortableMexicanSofa . logger . info ( message ) frags_to_remove = old_frag_identifiers - new_frag_identifiers translation . fragments . where ( identifier : frags_to_remove ) . destroy_all else message = "[CMS SEEDS] Failed to import Translation \n#{locale}" ComfortableMexicanSofa . logger . warn ( message ) end end translations_to_remove = old_translations - new_translations page . translations . where ( locale : translations_to_remove ) . destroy_all end
Importing translations for given page . They look like content . locale . html
1,890
def construct_fragments_attributes ( hash , record , path ) frag_identifiers = [ ] frag_attributes = hash . collect do | frag_header , frag_content | tag , identifier = frag_header . split frag_hash = { identifier : identifier , tag : tag } frag_identifiers << identifier case tag when "date" , "datetime" frag_hash [ :datetime ] = frag_content when "checkbox" frag_hash [ :boolean ] = frag_content when "file" , "files" files , file_ids_destroy = files_content ( record , identifier , path , frag_content ) frag_hash [ :files ] = files frag_hash [ :file_ids_destroy ] = file_ids_destroy else frag_hash [ :content ] = frag_content end frag_hash end [ frag_identifiers , frag_attributes ] end
Constructing frag attributes hash that can be assigned to page or translation also returning list of frag identifiers so we can destroy old ones
1,891
def files_content ( record , identifier , path , frag_content ) files = frag_content . split ( "\n" ) . collect do | filename | file_handler = File . open ( File . join ( path , filename ) ) { io : file_handler , filename : filename , content_type : MimeMagic . by_magic ( file_handler ) } end ids_destroy = [ ] if ( frag = record . fragments . find_by ( identifier : identifier ) ) ids_destroy = frag . attachments . pluck ( :id ) end [ files , ids_destroy ] end
Preparing fragment attachments . Returns hashes with file data for ActiveStorage and a list of ids of old attachements to destroy
1,892
def cms_fragment_render ( identifier , page = @cms_page ) node = page . fragment_nodes . detect { | n | n . identifier == identifier . to_s } return "" unless node node . renderable = true render inline : page . render ( [ node ] ) end
Same as cms_fragment_content but with cms tags expanded and rendered . Use it only if you know you got more stuff in the fragment content other than text because this is a potentially expensive call .
1,893
def cms_snippet_render ( identifier , cms_site = @cms_site ) cms_site ||= cms_site_detect snippet = cms_site &. snippets &. find_by_identifier ( identifier ) return "" unless snippet r = ComfortableMexicanSofa :: Content :: Renderer . new ( snippet ) render inline : r . render ( r . nodes ( r . tokenize ( snippet . content ) ) ) end
Same as cms_snippet_content but cms tags will be expanded . Note that there is no page context so snippet cannot contain fragment tags .
1,894
def comfy_paginate ( collection ) return unless collection if defined? ( WillPaginate ) will_paginate collection elsif defined? ( Kaminari ) paginate collection , theme : "comfy" end end
Wrapper to deal with Kaminari vs WillPaginate
1,895
def post ( path , body = '' , headers = { } ) headers = { 'Content-Type' => 'application/json' } . merge ( headers ) request ( :post , path , body , merge_default_headers ( headers ) ) end
HTTP methods with a body
1,896
def respond_to? ( method_name , _include_all = false ) if attrs . key? ( method_name . to_s ) true else super ( method_name ) end end
Checks if method_name is set in the attributes hash and returns true when found otherwise proxies the call to the superclass .
1,897
def method_missing ( method_name , * _args ) if attrs . key? ( method_name . to_s ) attrs [ method_name . to_s ] else super ( method_name ) end end
Overrides method_missing to check the attribute hash for resources matching method_name and proxies the call to the superclass if no match is found .
1,898
def fetch ( reload = false , query_params = { } ) return if expanded? && ! reload response = client . get ( url_with_query_params ( url , query_params ) ) set_attrs_from_response ( response ) @expanded = true end
Fetches the attributes for the specified resource from JIRA unless the resource is already expanded and the optional force reload flag is not set
1,899
def set_attrs_from_response ( response ) unless response . body . nil? || ( response . body . length < 2 ) json = self . class . parse_json ( response . body ) set_attrs ( json ) end end
Sets the attributes hash from a HTTPResponse object from JIRA if it is not nil or is not a json response .