id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
|
|---|---|---|---|---|---|---|---|---|---|---|---|
12,100
|
strongself/Generamba
|
lib/generamba/template/helpers/catalog_downloader.rb
|
Generamba.CatalogDownloader.update_all_catalogs_and_return_filepaths
|
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
|
ruby
|
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
|
[
"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.
@return [Array] An array of filepaths to downloaded catalogs
|
[
"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",
"."
] |
9ef343805f3a66f58bc36e120e822d5436a4da97
|
https://github.com/strongself/Generamba/blob/9ef343805f3a66f58bc36e120e822d5436a4da97/lib/generamba/template/helpers/catalog_downloader.rb#L12-L33
|
12,101
|
strongself/Generamba
|
lib/generamba/template/helpers/catalog_downloader.rb
|
Generamba.CatalogDownloader.download_catalog
|
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
|
ruby
|
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
|
[
"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
@param name [String] The name of the template catalog
@param url [String] The url of the repository
@return [Pathname] A filepath to the downloaded catalog
|
[
"Clones",
"a",
"template",
"catalog",
"from",
"a",
"remote",
"repository"
] |
9ef343805f3a66f58bc36e120e822d5436a4da97
|
https://github.com/strongself/Generamba/blob/9ef343805f3a66f58bc36e120e822d5436a4da97/lib/generamba/template/helpers/catalog_downloader.rb#L41-L56
|
12,102
|
strongself/Generamba
|
lib/generamba/template/installer/template_installer_factory.rb
|
Generamba.TemplateInstallerFactory.installer_for_type
|
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
|
ruby
|
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
|
[
"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
|
[
"Provides",
"the",
"appropriate",
"strategy",
"for",
"a",
"given",
"template",
"type"
] |
9ef343805f3a66f58bc36e120e822d5436a4da97
|
https://github.com/strongself/Generamba/blob/9ef343805f3a66f58bc36e120e822d5436a4da97/lib/generamba/template/installer/template_installer_factory.rb#L9-L20
|
12,103
|
strongself/Generamba
|
lib/generamba/template/installer/catalog_installer.rb
|
Generamba.CatalogInstaller.browse_catalog_for_a_template
|
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
|
ruby
|
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
|
[
"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
@param catalog_path [Pathname] A path to a catalog
@param template_name [String] A name of the template
@return [Pathname] A path to a template, if found
|
[
"Browses",
"a",
"given",
"catalog",
"and",
"returns",
"a",
"template",
"path"
] |
9ef343805f3a66f58bc36e120e822d5436a4da97
|
https://github.com/strongself/Generamba/blob/9ef343805f3a66f58bc36e120e822d5436a4da97/lib/generamba/template/installer/catalog_installer.rb#L63-L71
|
12,104
|
strongself/Generamba
|
lib/generamba/template/processor/template_processor.rb
|
Generamba.TemplateProcessor.install_templates
|
def install_templates(rambafile)
# We always clear previously installed templates to avoid conflicts in different versions
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
# Mapping hashes to model objects
templates = rambafile[TEMPLATES_KEY].map { |template_hash|
Generamba::TemplateDeclaration.new(template_hash)
}
catalogs = rambafile[CATALOGS_KEY]
# If there is at least one template from catalogs, we should update our local copy of the catalog
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
|
ruby
|
def install_templates(rambafile)
# We always clear previously installed templates to avoid conflicts in different versions
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
# Mapping hashes to model objects
templates = rambafile[TEMPLATES_KEY].map { |template_hash|
Generamba::TemplateDeclaration.new(template_hash)
}
catalogs = rambafile[CATALOGS_KEY]
# If there is at least one template from catalogs, we should update our local copy of the catalog
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
|
[
"def",
"install_templates",
"(",
"rambafile",
")",
"# We always clear previously installed templates to avoid conflicts in different versions",
"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",
"# Mapping hashes to model objects",
"templates",
"=",
"rambafile",
"[",
"TEMPLATES_KEY",
"]",
".",
"map",
"{",
"|",
"template_hash",
"|",
"Generamba",
"::",
"TemplateDeclaration",
".",
"new",
"(",
"template_hash",
")",
"}",
"catalogs",
"=",
"rambafile",
"[",
"CATALOGS_KEY",
"]",
"# If there is at least one template from catalogs, we should update our local copy of the catalog",
"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
|
[
"This",
"method",
"parses",
"Rambafile",
"serializes",
"templates",
"hashes",
"into",
"model",
"objects",
"and",
"install",
"them"
] |
9ef343805f3a66f58bc36e120e822d5436a4da97
|
https://github.com/strongself/Generamba/blob/9ef343805f3a66f58bc36e120e822d5436a4da97/lib/generamba/template/processor/template_processor.rb#L20-L44
|
12,105
|
strongself/Generamba
|
lib/generamba/template/processor/template_processor.rb
|
Generamba.TemplateProcessor.clear_installed_templates
|
def clear_installed_templates
install_path = Pathname.new(TEMPLATES_FOLDER)
FileUtils.rm_rf(Dir.glob(install_path))
end
|
ruby
|
def clear_installed_templates
install_path = Pathname.new(TEMPLATES_FOLDER)
FileUtils.rm_rf(Dir.glob(install_path))
end
|
[
"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
|
[
"Clears",
"all",
"of",
"the",
"currently",
"installed",
"templates"
] |
9ef343805f3a66f58bc36e120e822d5436a4da97
|
https://github.com/strongself/Generamba/blob/9ef343805f3a66f58bc36e120e822d5436a4da97/lib/generamba/template/processor/template_processor.rb#L49-L52
|
12,106
|
strongself/Generamba
|
lib/generamba/template/processor/template_processor.rb
|
Generamba.TemplateProcessor.update_catalogs_if_needed
|
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
|
ruby
|
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
|
[
"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
|
[
"Clones",
"remote",
"template",
"catalogs",
"to",
"the",
"local",
"directory"
] |
9ef343805f3a66f58bc36e120e822d5436a4da97
|
https://github.com/strongself/Generamba/blob/9ef343805f3a66f58bc36e120e822d5436a4da97/lib/generamba/template/processor/template_processor.rb#L55-L73
|
12,107
|
CocoaPods/Xcodeproj
|
lib/xcodeproj/scheme.rb
|
Xcodeproj.XCScheme.configure_with_targets
|
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
|
ruby
|
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
|
[
"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
@param [String] file_path
The path of the existing .xcscheme file. If nil will create an empty scheme
Convenience method to quickly add app and test targets to a new scheme.
It will add the runnable_target to the Build, Launch and Profile actions
and the test_target to the Build and Test actions
@param [Xcodeproj::Project::Object::PBXAbstractTarget] runnable_target
The target to use for the 'Run', 'Profile' and 'Analyze' actions
@param [Xcodeproj::Project::Object::PBXAbstractTarget] test_target
The target to use for the 'Test' action
@param [Boolean] launch_target
Determines if the runnable_target is launchable.
|
[
"Create",
"a",
"XCScheme",
"either",
"from",
"scratch",
"or",
"using",
"an",
"existing",
"file"
] |
3be1684437a6f8e69c7836ad4c85a2b78663272f
|
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/scheme.rb#L72-L81
|
12,108
|
CocoaPods/Xcodeproj
|
lib/xcodeproj/scheme.rb
|
Xcodeproj.XCScheme.set_launch_target
|
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
|
ruby
|
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
|
[
"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.
@param [Xcodeproj::Project::Object::AbstractTarget] build_target
A target used by scheme in the launch step.
|
[
"Sets",
"a",
"runnable",
"target",
"to",
"be",
"the",
"target",
"of",
"the",
"launch",
"action",
"of",
"the",
"scheme",
"."
] |
3be1684437a6f8e69c7836ad4c85a2b78663272f
|
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/scheme.rb#L220-L229
|
12,109
|
CocoaPods/Xcodeproj
|
lib/xcodeproj/scheme.rb
|
Xcodeproj.XCScheme.save_as
|
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
|
ruby
|
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
|
[
"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.
@param [String, Pathname] project_path
The path where the ".xcscheme" file should be stored.
@param [String] name
The name of the scheme, to have ".xcscheme" appended.
@param [Boolean] shared
true => if the scheme must be a shared scheme (default value)
false => if the scheme must be a user scheme
@return [void]
@example Saving a scheme
scheme.save_as('path/to/Project.xcodeproj') #=> true
|
[
"Serializes",
"the",
"current",
"state",
"of",
"the",
"object",
"to",
"a",
".",
"xcscheme",
"file",
"."
] |
3be1684437a6f8e69c7836ad4c85a2b78663272f
|
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/scheme.rb#L310-L322
|
12,110
|
CocoaPods/Xcodeproj
|
lib/xcodeproj/project.rb
|
Xcodeproj.Project.initialize_from_file
|
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
# Projects can have product_ref_groups that are not listed in the main_groups["Products"]
root_object.product_ref_group ||= root_object.main_group['Products'] || root_object.main_group.new_group('Products')
end
|
ruby
|
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
# Projects can have product_ref_groups that are not listed in the main_groups["Products"]
root_object.product_ref_group ||= root_object.main_group['Products'] || root_object.main_group.new_group('Products')
end
|
[
"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",
"# Projects can have product_ref_groups that are not listed in the main_groups[\"Products\"]",
"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.
|
[
"Initializes",
"the",
"instance",
"with",
"the",
"project",
"stored",
"in",
"the",
"path",
"attribute",
"."
] |
3be1684437a6f8e69c7836ad4c85a2b78663272f
|
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/project.rb#L208-L232
|
12,111
|
CocoaPods/Xcodeproj
|
lib/xcodeproj/project.rb
|
Xcodeproj.Project.to_tree_hash
|
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
|
ruby
|
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
|
[
"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.
This method is designed to work in conjunction with {Hash#recursive_diff}
to provide a complete, yet readable, diff of two projects *not* affected
by differences in UUIDs.
@return [Hash] a hash representation of the project different from the
plist one.
|
[
"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",
"."
] |
3be1684437a6f8e69c7836ad4c85a2b78663272f
|
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/project.rb#L320-L329
|
12,112
|
CocoaPods/Xcodeproj
|
lib/xcodeproj/project.rb
|
Xcodeproj.Project.generate_available_uuid_list
|
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
|
ruby
|
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
|
[
"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.
@param [Integer] count
the number of UUIDs that should be generated.
@note This method might generated a minor number of uniques UUIDs than
the given count, because some might be duplicated a thus will be
discarded.
@return [void]
|
[
"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",
"."
] |
3be1684437a6f8e69c7836ad4c85a2b78663272f
|
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/project.rb#L479-L484
|
12,113
|
CocoaPods/Xcodeproj
|
lib/xcodeproj/project.rb
|
Xcodeproj.Project.reference_for_path
|
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
|
ruby
|
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
|
[
"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.
@param [#to_s] absolute_path
The absolute path of the file whose reference is needed.
@return [PBXFileReference] The file reference.
@return [Nil] If no file reference could be found.
|
[
"Returns",
"the",
"file",
"reference",
"for",
"the",
"given",
"absolute",
"path",
"."
] |
3be1684437a6f8e69c7836ad4c85a2b78663272f
|
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/project.rb#L553-L563
|
12,114
|
CocoaPods/Xcodeproj
|
lib/xcodeproj/project.rb
|
Xcodeproj.Project.embedded_targets_in_native_target
|
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
|
ruby
|
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
|
[
"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
@param [PBXNativeTarget] native target to check for
embedded targets
@return [Array<PBXNativeTarget>] A list of all targets that
are embedded in the passed in target
|
[
"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"
] |
3be1684437a6f8e69c7836ad4c85a2b78663272f
|
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/project.rb#L590-L594
|
12,115
|
CocoaPods/Xcodeproj
|
lib/xcodeproj/project.rb
|
Xcodeproj.Project.host_targets_for_embedded_target
|
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
|
ruby
|
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
|
[
"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.
@param [PBXNativeTarget] native target that might be embedded
in another target
@return [Array<PBXNativeTarget>] the native targets that host the
embedded target
|
[
"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",
"."
] |
3be1684437a6f8e69c7836ad4c85a2b78663272f
|
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/project.rb#L606-L611
|
12,116
|
CocoaPods/Xcodeproj
|
lib/xcodeproj/project.rb
|
Xcodeproj.Project.new_resources_bundle
|
def new_resources_bundle(name, platform, product_group = nil)
product_group ||= products_group
ProjectHelper.new_resources_bundle(self, name, platform, product_group)
end
|
ruby
|
def new_resources_bundle(name, platform, product_group = nil)
product_group ||= products_group
ProjectHelper.new_resources_bundle(self, name, platform, product_group)
end
|
[
"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.
The target is configured for the given platform and its file reference it
is added to the {products_group}.
The target is pre-populated with common build settings
@param [String] name
the name of the resources bundle.
@param [Symbol] platform
the platform of the resources bundle. Can be `:ios` or `:osx`.
@return [PBXNativeTarget] the target.
|
[
"Creates",
"a",
"new",
"resource",
"bundles",
"target",
"and",
"adds",
"it",
"to",
"the",
"project",
"."
] |
3be1684437a6f8e69c7836ad4c85a2b78663272f
|
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/project.rb#L734-L737
|
12,117
|
CocoaPods/Xcodeproj
|
lib/xcodeproj/project.rb
|
Xcodeproj.Project.add_build_configuration
|
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
|
ruby
|
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
|
[
"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.
@param [String] name
The name of the build configuration.
@param [Symbol] type
The type of the build configuration used to populate the build
settings, must be :debug or :release.
@return [XCBuildConfiguration] The new build configuration.
|
[
"Adds",
"a",
"new",
"build",
"configuration",
"to",
"the",
"project",
"and",
"populates",
"its",
"with",
"default",
"settings",
"according",
"to",
"the",
"provided",
"type",
"."
] |
3be1684437a6f8e69c7836ad4c85a2b78663272f
|
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/project.rb#L782-L796
|
12,118
|
CocoaPods/Xcodeproj
|
lib/xcodeproj/config.rb
|
Xcodeproj.Config.save_as
|
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
|
ruby
|
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
|
[
"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.
@param [Pathname] pathname
The file where the data should be written to.
@return [void]
|
[
"Writes",
"the",
"serialized",
"representation",
"of",
"the",
"internal",
"data",
"to",
"the",
"given",
"path",
"."
] |
3be1684437a6f8e69c7836ad4c85a2b78663272f
|
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/config.rb#L104-L110
|
12,119
|
CocoaPods/Xcodeproj
|
lib/xcodeproj/config.rb
|
Xcodeproj.Config.hash_from_file_content
|
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
|
ruby
|
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
|
[
"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.
@param [String] string
The string representation of an xcconfig file.
@return [Hash] the hash containing the xcconfig data.
|
[
"Returns",
"a",
"hash",
"from",
"the",
"string",
"representation",
"of",
"an",
"Xcconfig",
"file",
"."
] |
3be1684437a6f8e69c7836ad4c85a2b78663272f
|
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/config.rb#L273-L287
|
12,120
|
CocoaPods/Xcodeproj
|
lib/xcodeproj/config.rb
|
Xcodeproj.Config.merge_attributes!
|
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
|
ruby
|
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
|
[
"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.
@param [Hash] attributes
The attributes hash to merge into @attributes.
@return [void]
|
[
"Merges",
"the",
"given",
"attributes",
"hash",
"while",
"ensuring",
"values",
"are",
"not",
"duplicated",
"."
] |
3be1684437a6f8e69c7836ad4c85a2b78663272f
|
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/config.rb#L296-L310
|
12,121
|
CocoaPods/Xcodeproj
|
lib/xcodeproj/config.rb
|
Xcodeproj.Config.extract_key_value
|
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
|
ruby
|
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
|
[
"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.
@param [String] line
the line to process.
@return [Array] A tuple where the first entry is the key and the second
entry is the value.
|
[
"Returns",
"the",
"key",
"and",
"the",
"value",
"described",
"by",
"the",
"given",
"line",
"of",
"an",
"xcconfig",
"."
] |
3be1684437a6f8e69c7836ad4c85a2b78663272f
|
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/config.rb#L345-L354
|
12,122
|
CocoaPods/Xcodeproj
|
spec/spec_helper/project_helper.rb
|
SpecHelper.ProjectHelper.compare_settings
|
def compare_settings(produced, expected, params)
it 'should match build settings' do
# Find faulty settings in different categories
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
# Build pretty description for what is going on
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
# Expect
faulty_settings = missing_settings + unexpected_settings + wrong_settings
faulty_settings.should.satisfy(description * "\n") do
faulty_settings.length == 0
end
end
end
|
ruby
|
def compare_settings(produced, expected, params)
it 'should match build settings' do
# Find faulty settings in different categories
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
# Build pretty description for what is going on
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
# Expect
faulty_settings = missing_settings + unexpected_settings + wrong_settings
faulty_settings.should.satisfy(description * "\n") do
faulty_settings.length == 0
end
end
end
|
[
"def",
"compare_settings",
"(",
"produced",
",",
"expected",
",",
"params",
")",
"it",
"'should match build settings'",
"do",
"# Find faulty settings in different categories",
"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",
"# Build pretty description for what is going on",
"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",
"# Expect",
"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.
@param [Hash{String => String}] produced
the produced build settings.
@param [Hash{String => String}] expected
the expected build settings.
@param [#to_s] params
the parameters used to construct the produced build settings.
|
[
"Generates",
"test",
"cases",
"to",
"compare",
"two",
"settings",
"hashes",
"."
] |
3be1684437a6f8e69c7836ad4c85a2b78663272f
|
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/spec/spec_helper/project_helper.rb#L29-L68
|
12,123
|
CocoaPods/Xcodeproj
|
spec/spec_helper/project_helper.rb
|
SpecHelper.ProjectHelper.load_settings
|
def load_settings(path, type)
# Load fixture
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
# Filter exclusions
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
|
ruby
|
def load_settings(path, type)
# Load fixture
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
# Filter exclusions
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
|
[
"def",
"load_settings",
"(",
"path",
",",
"type",
")",
"# Load fixture",
"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",
"# Filter exclusions",
"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
@param [String] path
the directory, where the fixture set is located.
@param [Symbol] type
the type, where the specific
@param [Hash{String => String}]
the build settings
|
[
"Load",
"settings",
"from",
"fixtures"
] |
3be1684437a6f8e69c7836ad4c85a2b78663272f
|
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/spec/spec_helper/project_helper.rb#L81-L96
|
12,124
|
CocoaPods/Xcodeproj
|
lib/xcodeproj/workspace.rb
|
Xcodeproj.Workspace.save_as
|
def save_as(path)
FileUtils.mkdir_p(path)
File.open(File.join(path, 'contents.xcworkspacedata'), 'w') do |out|
out << to_s
end
end
|
ruby
|
def save_as(path)
FileUtils.mkdir_p(path)
File.open(File.join(path, 'contents.xcworkspacedata'), 'w') do |out|
out << to_s
end
end
|
[
"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.
@param [String] path
the path where to save the project.
@return [void]
|
[
"Saves",
"the",
"workspace",
"at",
"the",
"given",
"xcworkspace",
"path",
"."
] |
3be1684437a6f8e69c7836ad4c85a2b78663272f
|
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/workspace.rb#L179-L184
|
12,125
|
CocoaPods/Xcodeproj
|
lib/xcodeproj/workspace.rb
|
Xcodeproj.Workspace.load_schemes_from_project
|
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
|
ruby
|
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
|
[
"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
@param [String] project_full_path
project full path
@return [void]
|
[
"Load",
"all",
"schemes",
"from",
"project"
] |
3be1684437a6f8e69c7836ad4c85a2b78663272f
|
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/workspace.rb#L224-L229
|
12,126
|
kmuto/review
|
lib/epubmaker/epubcommon.rb
|
EPUBMaker.EPUBCommon.container
|
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
|
ruby
|
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
|
[
"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.
|
[
"Return",
"container",
"content",
"."
] |
77d1273e671663f05db2992281fd891b776badf0
|
https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/epubcommon.rb#L118-L123
|
12,127
|
kmuto/review
|
lib/epubmaker/epubcommon.rb
|
EPUBMaker.EPUBCommon.mytoc
|
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
|
ruby
|
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
|
[
"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.
|
[
"Return",
"own",
"toc",
"content",
"."
] |
77d1273e671663f05db2992281fd891b776badf0
|
https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/epubcommon.rb#L291-L310
|
12,128
|
kmuto/review
|
lib/review/compiler.rb
|
ReVIEW.Compiler.compile_inline
|
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
|
ruby
|
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
|
[
"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
|
[
"called",
"from",
"strategy"
] |
77d1273e671663f05db2992281fd891b776badf0
|
https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/review/compiler.rb#L572-L584
|
12,129
|
kmuto/review
|
lib/epubmaker/producer.rb
|
EPUBMaker.Producer.load
|
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
|
ruby
|
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
|
[
"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.
|
[
"Take",
"YAML",
"+",
"file",
"+",
"and",
"update",
"parameter",
"hash",
"."
] |
77d1273e671663f05db2992281fd891b776badf0
|
https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/producer.rb#L40-L46
|
12,130
|
kmuto/review
|
lib/epubmaker/producer.rb
|
EPUBMaker.Producer.merge_config
|
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
|
ruby
|
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
|
[
"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+.
|
[
"Update",
"parameters",
"by",
"merging",
"from",
"new",
"parameter",
"hash",
"+",
"config",
"+",
"."
] |
77d1273e671663f05db2992281fd891b776badf0
|
https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/producer.rb#L77-L95
|
12,131
|
kmuto/review
|
lib/epubmaker/producer.rb
|
EPUBMaker.Producer.mimetype
|
def mimetype(wobj)
s = @epub.mimetype
if !s.nil? && !wobj.nil?
wobj.print s
end
end
|
ruby
|
def mimetype(wobj)
s = @epub.mimetype
if !s.nil? && !wobj.nil?
wobj.print s
end
end
|
[
"def",
"mimetype",
"(",
"wobj",
")",
"s",
"=",
"@epub",
".",
"mimetype",
"if",
"!",
"s",
".",
"nil?",
"&&",
"!",
"wobj",
".",
"nil?",
"wobj",
".",
"print",
"s",
"end",
"end"
] |
Write mimetype file to IO object +wobj+.
|
[
"Write",
"mimetype",
"file",
"to",
"IO",
"object",
"+",
"wobj",
"+",
"."
] |
77d1273e671663f05db2992281fd891b776badf0
|
https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/producer.rb#L98-L103
|
12,132
|
kmuto/review
|
lib/epubmaker/producer.rb
|
EPUBMaker.Producer.opf
|
def opf(wobj)
s = @epub.opf
if !s.nil? && !wobj.nil?
wobj.puts s
end
end
|
ruby
|
def opf(wobj)
s = @epub.opf
if !s.nil? && !wobj.nil?
wobj.puts s
end
end
|
[
"def",
"opf",
"(",
"wobj",
")",
"s",
"=",
"@epub",
".",
"opf",
"if",
"!",
"s",
".",
"nil?",
"&&",
"!",
"wobj",
".",
"nil?",
"wobj",
".",
"puts",
"s",
"end",
"end"
] |
Write opf file to IO object +wobj+.
|
[
"Write",
"opf",
"file",
"to",
"IO",
"object",
"+",
"wobj",
"+",
"."
] |
77d1273e671663f05db2992281fd891b776badf0
|
https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/producer.rb#L106-L111
|
12,133
|
kmuto/review
|
lib/epubmaker/producer.rb
|
EPUBMaker.Producer.ncx
|
def ncx(wobj, indentarray = [])
s = @epub.ncx(indentarray)
if !s.nil? && !wobj.nil?
wobj.puts s
end
end
|
ruby
|
def ncx(wobj, indentarray = [])
s = @epub.ncx(indentarray)
if !s.nil? && !wobj.nil?
wobj.puts s
end
end
|
[
"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.
|
[
"Write",
"ncx",
"file",
"to",
"IO",
"object",
"+",
"wobj",
"+",
".",
"+",
"indentarray",
"+",
"defines",
"prefix",
"string",
"for",
"each",
"level",
"."
] |
77d1273e671663f05db2992281fd891b776badf0
|
https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/producer.rb#L115-L120
|
12,134
|
kmuto/review
|
lib/epubmaker/producer.rb
|
EPUBMaker.Producer.container
|
def container(wobj)
s = @epub.container
if !s.nil? && !wobj.nil?
wobj.puts s
end
end
|
ruby
|
def container(wobj)
s = @epub.container
if !s.nil? && !wobj.nil?
wobj.puts s
end
end
|
[
"def",
"container",
"(",
"wobj",
")",
"s",
"=",
"@epub",
".",
"container",
"if",
"!",
"s",
".",
"nil?",
"&&",
"!",
"wobj",
".",
"nil?",
"wobj",
".",
"puts",
"s",
"end",
"end"
] |
Write container file to IO object +wobj+.
|
[
"Write",
"container",
"file",
"to",
"IO",
"object",
"+",
"wobj",
"+",
"."
] |
77d1273e671663f05db2992281fd891b776badf0
|
https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/producer.rb#L123-L128
|
12,135
|
kmuto/review
|
lib/epubmaker/producer.rb
|
EPUBMaker.Producer.colophon
|
def colophon(wobj)
s = @epub.colophon
if !s.nil? && !wobj.nil?
wobj.puts s
end
end
|
ruby
|
def colophon(wobj)
s = @epub.colophon
if !s.nil? && !wobj.nil?
wobj.puts s
end
end
|
[
"def",
"colophon",
"(",
"wobj",
")",
"s",
"=",
"@epub",
".",
"colophon",
"if",
"!",
"s",
".",
"nil?",
"&&",
"!",
"wobj",
".",
"nil?",
"wobj",
".",
"puts",
"s",
"end",
"end"
] |
Write colophon file to IO object +wobj+.
|
[
"Write",
"colophon",
"file",
"to",
"IO",
"object",
"+",
"wobj",
"+",
"."
] |
77d1273e671663f05db2992281fd891b776badf0
|
https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/producer.rb#L150-L155
|
12,136
|
kmuto/review
|
lib/epubmaker/producer.rb
|
EPUBMaker.Producer.mytoc
|
def mytoc(wobj)
s = @epub.mytoc
if !s.nil? && !wobj.nil?
wobj.puts s
end
end
|
ruby
|
def mytoc(wobj)
s = @epub.mytoc
if !s.nil? && !wobj.nil?
wobj.puts s
end
end
|
[
"def",
"mytoc",
"(",
"wobj",
")",
"s",
"=",
"@epub",
".",
"mytoc",
"if",
"!",
"s",
".",
"nil?",
"&&",
"!",
"wobj",
".",
"nil?",
"wobj",
".",
"puts",
"s",
"end",
"end"
] |
Write own toc file to IO object +wobj+.
|
[
"Write",
"own",
"toc",
"file",
"to",
"IO",
"object",
"+",
"wobj",
"+",
"."
] |
77d1273e671663f05db2992281fd891b776badf0
|
https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/producer.rb#L158-L163
|
12,137
|
kmuto/review
|
lib/epubmaker/epubv2.rb
|
EPUBMaker.EPUBv2.ncx
|
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
|
ruby
|
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
|
[
"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.
|
[
"Return",
"ncx",
"content",
".",
"+",
"indentarray",
"+",
"has",
"prefix",
"marks",
"for",
"each",
"level",
"."
] |
77d1273e671663f05db2992281fd891b776badf0
|
https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/epubv2.rb#L114-L121
|
12,138
|
kmuto/review
|
lib/epubmaker/epubv2.rb
|
EPUBMaker.EPUBv2.produce
|
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
|
ruby
|
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
|
[
"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.
|
[
"Produce",
"EPUB",
"file",
"+",
"epubfile",
"+",
".",
"+",
"basedir",
"+",
"points",
"the",
"directory",
"has",
"contents",
".",
"+",
"tmpdir",
"+",
"defines",
"temporary",
"directory",
"."
] |
77d1273e671663f05db2992281fd891b776badf0
|
https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/epubv2.rb#L126-L141
|
12,139
|
kmuto/review
|
lib/review/latexbuilder.rb
|
ReVIEW.LATEXBuilder.inline_i
|
def inline_i(str)
if @book.config.check_version('2', exception: false)
macro('textit', escape(str))
else
macro('reviewit', escape(str))
end
end
|
ruby
|
def inline_i(str)
if @book.config.check_version('2', exception: false)
macro('textit', escape(str))
else
macro('reviewit', escape(str))
end
end
|
[
"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
|
[
"index",
"-",
">",
"italic"
] |
77d1273e671663f05db2992281fd891b776badf0
|
https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/review/latexbuilder.rb#L1022-L1028
|
12,140
|
kmuto/review
|
lib/review/yamlloader.rb
|
ReVIEW.YAMLLoader.load_file
|
def load_file(yamlfile)
file_queue = [File.expand_path(yamlfile)]
loaded_files = {}
yaml = {}
loop do
# Check exit condition
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))
# Check loop
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
|
ruby
|
def load_file(yamlfile)
file_queue = [File.expand_path(yamlfile)]
loaded_files = {}
yaml = {}
loop do
# Check exit condition
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))
# Check loop
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
|
[
"def",
"load_file",
"(",
"yamlfile",
")",
"file_queue",
"=",
"[",
"File",
".",
"expand_path",
"(",
"yamlfile",
")",
"]",
"loaded_files",
"=",
"{",
"}",
"yaml",
"=",
"{",
"}",
"loop",
"do",
"# Check exit condition",
"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",
")",
")",
"# Check loop",
"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
`inherit: [3.yml, 6.yml]` in 7.yml; `inherit: [1.yml, 2.yml]` in 3.yml; `inherit: [4.yml, 5.yml]` in 6.yml
=> 7.yml > 6.yml > 5.yml > 4.yml > 3.yml > 2.yml > 1.yml
|
[
"load",
"YAML",
"files"
] |
77d1273e671663f05db2992281fd891b776badf0
|
https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/review/yamlloader.rb#L13-L43
|
12,141
|
kmuto/review
|
lib/epubmaker/content.rb
|
EPUBMaker.Content.complement
|
def complement
if @id.nil?
@id = @file.gsub(%r{[\\/\. ]}, '-')
end
if @id =~ /\A[^a-z]/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
|
ruby
|
def complement
if @id.nil?
@id = @file.gsub(%r{[\\/\. ]}, '-')
end
if @id =~ /\A[^a-z]/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
|
[
"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.
|
[
"Complement",
"other",
"parameters",
"by",
"using",
"file",
"parameter",
"."
] |
77d1273e671663f05db2992281fd891b776badf0
|
https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/content.rb#L74-L108
|
12,142
|
splitrb/split
|
lib/split/trial.rb
|
Split.Trial.choose!
|
def choose!(context = nil)
@user.cleanup_old_experiments!
# Only run the process once
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
# Increment the number of participants since we are actually choosing a new 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
|
ruby
|
def choose!(context = nil)
@user.cleanup_old_experiments!
# Only run the process once
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
# Increment the number of participants since we are actually choosing a new 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
|
[
"def",
"choose!",
"(",
"context",
"=",
"nil",
")",
"@user",
".",
"cleanup_old_experiments!",
"# Only run the process once",
"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",
"# Increment the number of participants since we are actually choosing a new 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.
|
[
"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",
"."
] |
02f3f14f99288c3395910999cdb657f2ec5a06cd
|
https://github.com/splitrb/split/blob/02f3f14f99288c3395910999cdb657f2ec5a06cd/lib/split/trial.rb#L51-L87
|
12,143
|
brianmario/mysql2
|
lib/mysql2/client.rb
|
Mysql2.Client.parse_connect_attrs
|
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
|
ruby
|
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
|
[
"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
|
[
"Set",
"default",
"program_name",
"in",
"performance_schema",
".",
"session_connect_attrs",
"and",
"performance_schema",
".",
"session_account_connect_attrs"
] |
c8c346db72b5505740065d9de79b4a52081d5a57
|
https://github.com/brianmario/mysql2/blob/c8c346db72b5505740065d9de79b4a52081d5a57/lib/mysql2/client.rb#L120-L127
|
12,144
|
brianmario/mysql2
|
lib/mysql2/error.rb
|
Mysql2.Error.clean_message
|
def clean_message(message)
if @server_version && @server_version > 50500
message.encode(ENCODE_OPTS)
else
message.encode(Encoding::UTF_8, ENCODE_OPTS)
end
end
|
ruby
|
def clean_message(message)
if @server_version && @server_version > 50500
message.encode(ENCODE_OPTS)
else
message.encode(Encoding::UTF_8, ENCODE_OPTS)
end
end
|
[
"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.
See http://dev.mysql.com/doc/refman/5.5/en/charset-errors.html for
more context.
Before MySQL 5.5 error message template strings are in whatever encoding
is associated with the error message language.
See http://dev.mysql.com/doc/refman/5.1/en/error-message-language.html
for more information.
The issue is that the user-data inserted in the message could potentially
be in any encoding MySQL supports and is insert into the latin1, euckr or
koi8r string raw. Meaning there's a high probability the string will be
corrupt encoding-wise.
See http://dev.mysql.com/doc/refman/5.1/en/charset-errors.html for
more information.
So in an attempt to make sure the error message string is always in a valid
encoding, we'll assume UTF-8 and clean the string of anything that's not a
valid UTF-8 character.
Returns a valid UTF-8 string.
|
[
"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",
"."
] |
c8c346db72b5505740065d9de79b4a52081d5a57
|
https://github.com/brianmario/mysql2/blob/c8c346db72b5505740065d9de79b4a52081d5a57/lib/mysql2/error.rb#L92-L98
|
12,145
|
zipmark/rspec_api_documentation
|
lib/rspec_api_documentation/dsl.rb
|
RspecApiDocumentation.DSL.resource
|
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
|
ruby
|
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
|
[
"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
resource "Orders", :meta => :data do
# ...
end
Params:
+args+:: Glob of RSpec's `describe` arguments
+block+:: Block to pass into describe
|
[
"Custom",
"describe",
"block",
"that",
"sets",
"metadata",
"to",
"enable",
"the",
"rest",
"of",
"RAD"
] |
54fbfda3ec8ede5b3d871700ff69aabe89eafb2f
|
https://github.com/zipmark/rspec_api_documentation/blob/54fbfda3ec8ede5b3d871700ff69aabe89eafb2f/lib/rspec_api_documentation/dsl.rb#L20-L27
|
12,146
|
zipmark/rspec_api_documentation
|
lib/rspec_api_documentation/configuration.rb
|
RspecApiDocumentation.Configuration.define_group
|
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
|
ruby
|
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
|
[
"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
Automatically sets the `filter` to the group name, and the `docs_dir` to
a subfolder of the parent's `doc_dir` named the group name.
RspecApiDocumentation.configure do |config|
config.docs_dir = "doc/api"
config.define_group(:public) do |config|
# Default values
config.docs_dir = "doc/api/public"
config.filter = :public
end
end
Params:
+name+:: String name of the group
+block+:: Block configuration block
|
[
"Defines",
"a",
"new",
"sub",
"configuration"
] |
54fbfda3ec8ede5b3d871700ff69aabe89eafb2f
|
https://github.com/zipmark/rspec_api_documentation/blob/54fbfda3ec8ede5b3d871700ff69aabe89eafb2f/lib/rspec_api_documentation/configuration.rb#L33-L39
|
12,147
|
brunofacca/active-record-query-trace
|
lib/active_record_query_trace.rb
|
ActiveRecordQueryTrace.CustomLogSubscriber.lines_to_display
|
def lines_to_display(full_trace)
ActiveRecordQueryTrace.lines.zero? ? full_trace : full_trace.first(ActiveRecordQueryTrace.lines)
end
|
ruby
|
def lines_to_display(full_trace)
ActiveRecordQueryTrace.lines.zero? ? full_trace : full_trace.first(ActiveRecordQueryTrace.lines)
end
|
[
"def",
"lines_to_display",
"(",
"full_trace",
")",
"ActiveRecordQueryTrace",
".",
"lines",
".",
"zero?",
"?",
"full_trace",
":",
"full_trace",
".",
"first",
"(",
"ActiveRecordQueryTrace",
".",
"lines",
")",
"end"
] |
Must be called after the backtrace cleaner.
|
[
"Must",
"be",
"called",
"after",
"the",
"backtrace",
"cleaner",
"."
] |
9584d5d49cfc2170271f75bbf2773b46145e1be4
|
https://github.com/brunofacca/active-record-query-trace/blob/9584d5d49cfc2170271f75bbf2773b46145e1be4/lib/active_record_query_trace.rb#L101-L103
|
12,148
|
brunofacca/active-record-query-trace
|
lib/active_record_query_trace.rb
|
ActiveRecordQueryTrace.CustomLogSubscriber.setup_backtrace_cleaner_path
|
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
|
ruby
|
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
|
[
"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.
|
[
"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",
"."
] |
9584d5d49cfc2170271f75bbf2773b46145e1be4
|
https://github.com/brunofacca/active-record-query-trace/blob/9584d5d49cfc2170271f75bbf2773b46145e1be4/lib/active_record_query_trace.rb#L152-L155
|
12,149
|
stripe/stripe-ruby
|
lib/stripe/stripe_object.rb
|
Stripe.StripeObject.update_attributes
|
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
|
ruby
|
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
|
[
"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.
This is a version of +update_attributes+ that takes some extra options
for internal use.
==== Attributes
* +values+ - Hash of values to use to update the current attributes of
the object.
* +opts+ - Options for +StripeObject+ like an API key that will be reused
on subsequent API calls.
==== Options
* +:dirty+ - Whether values should be initiated as "dirty" (unsaved) and
which applies only to new StripeObjects being initiated under this
StripeObject. Defaults to true.
|
[
"Mass",
"assigns",
"attributes",
"on",
"the",
"model",
"."
] |
322a8c60be8a9b9ac8aad8857864680a32176935
|
https://github.com/stripe/stripe-ruby/blob/322a8c60be8a9b9ac8aad8857864680a32176935/lib/stripe/stripe_object.rb#L156-L163
|
12,150
|
stripe/stripe-ruby
|
lib/stripe/stripe_object.rb
|
Stripe.StripeObject.empty_values
|
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
|
ruby
|
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
|
[
"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.
|
[
"Returns",
"a",
"hash",
"of",
"empty",
"values",
"for",
"all",
"the",
"values",
"that",
"are",
"in",
"the",
"given",
"StripeObject",
"."
] |
322a8c60be8a9b9ac8aad8857864680a32176935
|
https://github.com/stripe/stripe-ruby/blob/322a8c60be8a9b9ac8aad8857864680a32176935/lib/stripe/stripe_object.rb#L556-L567
|
12,151
|
stripe/stripe-ruby
|
lib/stripe/list_object.rb
|
Stripe.ListObject.auto_paging_each
|
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
|
ruby
|
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
|
[
"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.
Note that this method will make as many API calls as necessary to fetch
all resources. For more granular control, please see +each+ and
+next_page+.
|
[
"Iterates",
"through",
"each",
"resource",
"in",
"all",
"pages",
"making",
"additional",
"fetches",
"to",
"the",
"API",
"as",
"necessary",
"."
] |
322a8c60be8a9b9ac8aad8857864680a32176935
|
https://github.com/stripe/stripe-ruby/blob/322a8c60be8a9b9ac8aad8857864680a32176935/lib/stripe/list_object.rb#L53-L62
|
12,152
|
stripe/stripe-ruby
|
lib/stripe/stripe_client.rb
|
Stripe.StripeClient.format_app_info
|
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
|
ruby
|
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
|
[
"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.
|
[
"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",
"."
] |
322a8c60be8a9b9ac8aad8857864680a32176935
|
https://github.com/stripe/stripe-ruby/blob/322a8c60be8a9b9ac8aad8857864680a32176935/lib/stripe/stripe_client.rb#L319-L324
|
12,153
|
stripe/stripe-ruby
|
lib/stripe/stripe_client.rb
|
Stripe.StripeClient.specific_oauth_error
|
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
# We'd prefer that all errors are typed, but we create a generic
# OAuthError in case we run into a code that we don't recognize.
OAuth::OAuthError.new(*args)
end
end
|
ruby
|
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
# We'd prefer that all errors are typed, but we create a generic
# OAuthError in case we run into a code that we don't recognize.
OAuth::OAuthError.new(*args)
end
end
|
[
"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",
"# We'd prefer that all errors are typed, but we create a generic",
"# OAuthError in case we run into a code that we don't recognize.",
"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.
|
[
"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",
"."
] |
322a8c60be8a9b9ac8aad8857864680a32176935
|
https://github.com/stripe/stripe-ruby/blob/322a8c60be8a9b9ac8aad8857864680a32176935/lib/stripe/stripe_client.rb#L398-L425
|
12,154
|
awesome-print/awesome_print
|
lib/awesome_print/ext/active_record.rb
|
AwesomePrint.ActiveRecord.awesome_active_record_instance
|
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
|
ruby
|
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
|
[
"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.
NOTE: by default only instance attributes (i.e. columns) are shown. To format
ActiveRecord instance as regular object showing its instance variables and
accessors use :raw => true option:
ap record, :raw => true
------------------------------------------------------------------------------
|
[
"Format",
"ActiveRecord",
"instance",
"object",
"."
] |
4564fd74721562cbef2443f7d97109bf9192343d
|
https://github.com/awesome-print/awesome_print/blob/4564fd74721562cbef2443f7d97109bf9192343d/lib/awesome_print/ext/active_record.rb#L43-L59
|
12,155
|
awesome-print/awesome_print
|
lib/awesome_print/ext/ripple.rb
|
AwesomePrint.Ripple.awesome_ripple_document_instance
|
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) # Should always be array or Ripple::EmbeddedDocument for embedded associations
hash
end
end
"#{object} " << awesome_hash(data)
end
|
ruby
|
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) # Should always be array or Ripple::EmbeddedDocument for embedded associations
hash
end
end
"#{object} " << awesome_hash(data)
end
|
[
"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",
")",
"# Should always be array or Ripple::EmbeddedDocument for embedded associations",
"hash",
"end",
"end",
"\"#{object} \"",
"<<",
"awesome_hash",
"(",
"data",
")",
"end"
] |
Format Ripple instance object.
NOTE: by default only instance attributes are shown. To format a Ripple document instance
as a regular object showing its instance variables and accessors use :raw => true option:
ap document, :raw => true
------------------------------------------------------------------------------
|
[
"Format",
"Ripple",
"instance",
"object",
"."
] |
4564fd74721562cbef2443f7d97109bf9192343d
|
https://github.com/awesome-print/awesome_print/blob/4564fd74721562cbef2443f7d97109bf9192343d/lib/awesome_print/ext/ripple.rb#L38-L56
|
12,156
|
awesome-print/awesome_print
|
lib/awesome_print/ext/mongo_mapper.rb
|
AwesomePrint.MongoMapper.awesome_mongo_mapper_instance
|
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
# Add in associations
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
|
ruby
|
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
# Add in associations
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
|
[
"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",
"# Add in associations",
"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.
NOTE: by default only instance attributes (i.e. keys) are shown. To format
MongoMapper instance as regular object showing its instance variables and
accessors use :raw => true option:
ap record, :raw => true
------------------------------------------------------------------------------
|
[
"Format",
"MongoMapper",
"instance",
"object",
"."
] |
4564fd74721562cbef2443f7d97109bf9192343d
|
https://github.com/awesome-print/awesome_print/blob/4564fd74721562cbef2443f7d97109bf9192343d/lib/awesome_print/ext/mongo_mapper.rb#L67-L91
|
12,157
|
awesome-print/awesome_print
|
lib/awesome_print/ext/action_view.rb
|
AwesomePrint.ActionView.ap_debug
|
def ap_debug(object, options = {})
object.ai(
options.merge(html: true)
).sub(
/^<pre([\s>])/,
'<pre class="debug_dump"\\1'
)
end
|
ruby
|
def ap_debug(object, options = {})
object.ai(
options.merge(html: true)
).sub(
/^<pre([\s>])/,
'<pre class="debug_dump"\\1'
)
end
|
[
"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.
|
[
"Use",
"HTML",
"colors",
"and",
"add",
"default",
"debug_dump",
"class",
"to",
"the",
"resulting",
"HTML",
"."
] |
4564fd74721562cbef2443f7d97109bf9192343d
|
https://github.com/awesome-print/awesome_print/blob/4564fd74721562cbef2443f7d97109bf9192343d/lib/awesome_print/ext/action_view.rb#L9-L16
|
12,158
|
comfy/comfortable-mexican-sofa
|
lib/comfortable_mexican_sofa/extensions/acts_as_tree.rb
|
ComfortableMexicanSofa::ActsAsTree.InstanceMethods.ancestors
|
def ancestors
node = self
nodes = []
nodes << node = node.parent while node.parent
nodes
end
|
ruby
|
def ancestors
node = self
nodes = []
nodes << node = node.parent while node.parent
nodes
end
|
[
"def",
"ancestors",
"node",
"=",
"self",
"nodes",
"=",
"[",
"]",
"nodes",
"<<",
"node",
"=",
"node",
".",
"parent",
"while",
"node",
".",
"parent",
"nodes",
"end"
] |
Returns list of ancestors, starting from parent until root.
subchild1.ancestors # => [child1, root]
|
[
"Returns",
"list",
"of",
"ancestors",
"starting",
"from",
"parent",
"until",
"root",
"."
] |
38a31428f6e2c07d5bda64f0371eebfb29a3abc4
|
https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/lib/comfortable_mexican_sofa/extensions/acts_as_tree.rb#L65-L70
|
12,159
|
comfy/comfortable-mexican-sofa
|
lib/comfortable_mexican_sofa/extensions/acts_as_tree.rb
|
ComfortableMexicanSofa::ActsAsTree.InstanceMethods.descendants
|
def descendants
nodes = []
children.each do |c|
nodes << c
nodes << c.descendants
end
nodes.flatten
end
|
ruby
|
def descendants
nodes = []
children.each do |c|
nodes << c
nodes << c.descendants
end
nodes.flatten
end
|
[
"def",
"descendants",
"nodes",
"=",
"[",
"]",
"children",
".",
"each",
"do",
"|",
"c",
"|",
"nodes",
"<<",
"c",
"nodes",
"<<",
"c",
".",
"descendants",
"end",
"nodes",
".",
"flatten",
"end"
] |
Returns all children and children of children
|
[
"Returns",
"all",
"children",
"and",
"children",
"of",
"children"
] |
38a31428f6e2c07d5bda64f0371eebfb29a3abc4
|
https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/lib/comfortable_mexican_sofa/extensions/acts_as_tree.rb#L73-L80
|
12,160
|
comfy/comfortable-mexican-sofa
|
lib/comfortable_mexican_sofa/seeds.rb
|
ComfortableMexicanSofa::Seeds.Exporter.export!
|
def export!(classes = nil)
classes ||= SEED_CLASSES
classes.each do |klass|
klass = "ComfortableMexicanSofa::Seeds::#{klass}::Exporter"
klass.constantize.new(from, to).export!
end
end
|
ruby
|
def export!(classes = nil)
classes ||= SEED_CLASSES
classes.each do |klass|
klass = "ComfortableMexicanSofa::Seeds::#{klass}::Exporter"
klass.constantize.new(from, to).export!
end
end
|
[
"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
|
[
"if",
"passed",
"nil",
"will",
"use",
"default",
"seed",
"classes"
] |
38a31428f6e2c07d5bda64f0371eebfb29a3abc4
|
https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/lib/comfortable_mexican_sofa/seeds.rb#L86-L92
|
12,161
|
comfy/comfortable-mexican-sofa
|
lib/comfortable_mexican_sofa/seeds.rb
|
ComfortableMexicanSofa::Seeds.Exporter.write_file_content
|
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
|
ruby
|
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
|
[
"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
|
[
"Writing",
"to",
"the",
"seed",
"file",
".",
"Takes",
"in",
"file",
"handler",
"and",
"array",
"of",
"hashes",
"with",
"header",
"and",
"content",
"keys"
] |
38a31428f6e2c07d5bda64f0371eebfb29a3abc4
|
https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/lib/comfortable_mexican_sofa/seeds.rb#L98-L105
|
12,162
|
comfy/comfortable-mexican-sofa
|
lib/comfortable_mexican_sofa/seeds/page/exporter.rb
|
ComfortableMexicanSofa::Seeds::Page.Exporter.fragments_data
|
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
|
ruby
|
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
|
[
"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
|
[
"Collecting",
"fragment",
"data",
"and",
"writing",
"attachment",
"files",
"to",
"disk"
] |
38a31428f6e2c07d5bda64f0371eebfb29a3abc4
|
https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/lib/comfortable_mexican_sofa/seeds/page/exporter.rb#L67-L89
|
12,163
|
comfy/comfortable-mexican-sofa
|
lib/comfortable_mexican_sofa/seeds/page/importer.rb
|
ComfortableMexicanSofa::Seeds::Page.Importer.import_translations
|
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{content\.(\w+)\.html})[1]
new_translations << locale
translation = page.translations.where(locale: locale).first_or_initialize
next unless fresh_seed?(translation, file_path)
# reading file content in, resulting in a hash
fragments_hash = parse_file_content(file_path)
# parsing attributes section
attributes_yaml = fragments_hash.delete("attributes")
attrs = YAML.safe_load(attributes_yaml)
# applying attributes
layout = site.layouts.find_by(identifier: attrs.delete("layout")) || page.try(:layout)
translation.attributes = attrs.merge(
layout: layout
)
# applying fragments
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)
# cleaning up old fragments
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
# Cleaning up removed translations
translations_to_remove = old_translations - new_translations
page.translations.where(locale: translations_to_remove).destroy_all
end
|
ruby
|
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{content\.(\w+)\.html})[1]
new_translations << locale
translation = page.translations.where(locale: locale).first_or_initialize
next unless fresh_seed?(translation, file_path)
# reading file content in, resulting in a hash
fragments_hash = parse_file_content(file_path)
# parsing attributes section
attributes_yaml = fragments_hash.delete("attributes")
attrs = YAML.safe_load(attributes_yaml)
# applying attributes
layout = site.layouts.find_by(identifier: attrs.delete("layout")) || page.try(:layout)
translation.attributes = attrs.merge(
layout: layout
)
# applying fragments
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)
# cleaning up old fragments
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
# Cleaning up removed translations
translations_to_remove = old_translations - new_translations
page.translations.where(locale: translations_to_remove).destroy_all
end
|
[
"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",
")",
"# reading file content in, resulting in a hash",
"fragments_hash",
"=",
"parse_file_content",
"(",
"file_path",
")",
"# parsing attributes section",
"attributes_yaml",
"=",
"fragments_hash",
".",
"delete",
"(",
"\"attributes\"",
")",
"attrs",
"=",
"YAML",
".",
"safe_load",
"(",
"attributes_yaml",
")",
"# applying attributes",
"layout",
"=",
"site",
".",
"layouts",
".",
"find_by",
"(",
"identifier",
":",
"attrs",
".",
"delete",
"(",
"\"layout\"",
")",
")",
"||",
"page",
".",
"try",
"(",
":layout",
")",
"translation",
".",
"attributes",
"=",
"attrs",
".",
"merge",
"(",
"layout",
":",
"layout",
")",
"# applying fragments",
"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",
")",
"# cleaning up old fragments",
"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",
"# Cleaning up removed translations",
"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`
|
[
"Importing",
"translations",
"for",
"given",
"page",
".",
"They",
"look",
"like",
"content",
".",
"locale",
".",
"html"
] |
38a31428f6e2c07d5bda64f0371eebfb29a3abc4
|
https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/lib/comfortable_mexican_sofa/seeds/page/importer.rb#L101-L150
|
12,164
|
comfy/comfortable-mexican-sofa
|
lib/comfortable_mexican_sofa/seeds/page/importer.rb
|
ComfortableMexicanSofa::Seeds::Page.Importer.construct_fragments_attributes
|
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
}
# tracking fragments that need removing later
frag_identifiers << identifier
# based on tag we need to cram content in proper place and proper format
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
|
ruby
|
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
}
# tracking fragments that need removing later
frag_identifiers << identifier
# based on tag we need to cram content in proper place and proper format
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
|
[
"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",
"}",
"# tracking fragments that need removing later",
"frag_identifiers",
"<<",
"identifier",
"# based on tag we need to cram content in proper place and proper format",
"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
|
[
"Constructing",
"frag",
"attributes",
"hash",
"that",
"can",
"be",
"assigned",
"to",
"page",
"or",
"translation",
"also",
"returning",
"list",
"of",
"frag",
"identifiers",
"so",
"we",
"can",
"destroy",
"old",
"ones"
] |
38a31428f6e2c07d5bda64f0371eebfb29a3abc4
|
https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/lib/comfortable_mexican_sofa/seeds/page/importer.rb#L154-L184
|
12,165
|
comfy/comfortable-mexican-sofa
|
lib/comfortable_mexican_sofa/seeds/page/importer.rb
|
ComfortableMexicanSofa::Seeds::Page.Importer.files_content
|
def files_content(record, identifier, path, frag_content)
# preparing attachments
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
# ensuring that old attachments get removed
ids_destroy = []
if (frag = record.fragments.find_by(identifier: identifier))
ids_destroy = frag.attachments.pluck(:id)
end
[files, ids_destroy]
end
|
ruby
|
def files_content(record, identifier, path, frag_content)
# preparing attachments
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
# ensuring that old attachments get removed
ids_destroy = []
if (frag = record.fragments.find_by(identifier: identifier))
ids_destroy = frag.attachments.pluck(:id)
end
[files, ids_destroy]
end
|
[
"def",
"files_content",
"(",
"record",
",",
"identifier",
",",
"path",
",",
"frag_content",
")",
"# preparing attachments",
"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",
"# ensuring that old attachments get removed",
"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
|
[
"Preparing",
"fragment",
"attachments",
".",
"Returns",
"hashes",
"with",
"file",
"data",
"for",
"ActiveStorage",
"and",
"a",
"list",
"of",
"ids",
"of",
"old",
"attachements",
"to",
"destroy"
] |
38a31428f6e2c07d5bda64f0371eebfb29a3abc4
|
https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/lib/comfortable_mexican_sofa/seeds/page/importer.rb#L188-L206
|
12,166
|
comfy/comfortable-mexican-sofa
|
app/helpers/comfy/cms_helper.rb
|
Comfy.CmsHelper.cms_fragment_render
|
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
|
ruby
|
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
|
[
"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.
|
[
"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",
"."
] |
38a31428f6e2c07d5bda64f0371eebfb29a3abc4
|
https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/app/helpers/comfy/cms_helper.rb#L29-L34
|
12,167
|
comfy/comfortable-mexican-sofa
|
app/helpers/comfy/cms_helper.rb
|
Comfy.CmsHelper.cms_snippet_render
|
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
|
ruby
|
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
|
[
"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.
|
[
"Same",
"as",
"cms_snippet_content",
"but",
"cms",
"tags",
"will",
"be",
"expanded",
".",
"Note",
"that",
"there",
"is",
"no",
"page",
"context",
"so",
"snippet",
"cannot",
"contain",
"fragment",
"tags",
"."
] |
38a31428f6e2c07d5bda64f0371eebfb29a3abc4
|
https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/app/helpers/comfy/cms_helper.rb#L48-L54
|
12,168
|
comfy/comfortable-mexican-sofa
|
app/helpers/comfy/cms_helper.rb
|
Comfy.CmsHelper.comfy_paginate
|
def comfy_paginate(collection)
return unless collection
if defined?(WillPaginate)
will_paginate collection
elsif defined?(Kaminari)
paginate collection, theme: "comfy"
end
end
|
ruby
|
def comfy_paginate(collection)
return unless collection
if defined?(WillPaginate)
will_paginate collection
elsif defined?(Kaminari)
paginate collection, theme: "comfy"
end
end
|
[
"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
|
[
"Wrapper",
"to",
"deal",
"with",
"Kaminari",
"vs",
"WillPaginate"
] |
38a31428f6e2c07d5bda64f0371eebfb29a3abc4
|
https://github.com/comfy/comfortable-mexican-sofa/blob/38a31428f6e2c07d5bda64f0371eebfb29a3abc4/app/helpers/comfy/cms_helper.rb#L63-L70
|
12,169
|
sumoheavy/jira-ruby
|
lib/jira/client.rb
|
JIRA.Client.post
|
def post(path, body = '', headers = {})
headers = { 'Content-Type' => 'application/json' }.merge(headers)
request(:post, path, body, merge_default_headers(headers))
end
|
ruby
|
def post(path, body = '', headers = {})
headers = { 'Content-Type' => 'application/json' }.merge(headers)
request(:post, path, body, merge_default_headers(headers))
end
|
[
"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
|
[
"HTTP",
"methods",
"with",
"a",
"body"
] |
25e896f227ab81c528e9678708cb546d2f62f018
|
https://github.com/sumoheavy/jira-ruby/blob/25e896f227ab81c528e9678708cb546d2f62f018/lib/jira/client.rb#L228-L231
|
12,170
|
sumoheavy/jira-ruby
|
lib/jira/base.rb
|
JIRA.Base.respond_to?
|
def respond_to?(method_name, _include_all = false)
if attrs.key?(method_name.to_s)
true
else
super(method_name)
end
end
|
ruby
|
def respond_to?(method_name, _include_all = false)
if attrs.key?(method_name.to_s)
true
else
super(method_name)
end
end
|
[
"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.
|
[
"Checks",
"if",
"method_name",
"is",
"set",
"in",
"the",
"attributes",
"hash",
"and",
"returns",
"true",
"when",
"found",
"otherwise",
"proxies",
"the",
"call",
"to",
"the",
"superclass",
"."
] |
25e896f227ab81c528e9678708cb546d2f62f018
|
https://github.com/sumoheavy/jira-ruby/blob/25e896f227ab81c528e9678708cb546d2f62f018/lib/jira/base.rb#L290-L296
|
12,171
|
sumoheavy/jira-ruby
|
lib/jira/base.rb
|
JIRA.Base.method_missing
|
def method_missing(method_name, *_args)
if attrs.key?(method_name.to_s)
attrs[method_name.to_s]
else
super(method_name)
end
end
|
ruby
|
def method_missing(method_name, *_args)
if attrs.key?(method_name.to_s)
attrs[method_name.to_s]
else
super(method_name)
end
end
|
[
"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.
|
[
"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",
"."
] |
25e896f227ab81c528e9678708cb546d2f62f018
|
https://github.com/sumoheavy/jira-ruby/blob/25e896f227ab81c528e9678708cb546d2f62f018/lib/jira/base.rb#L301-L307
|
12,172
|
sumoheavy/jira-ruby
|
lib/jira/base.rb
|
JIRA.Base.fetch
|
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
|
ruby
|
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
|
[
"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
|
[
"Fetches",
"the",
"attributes",
"for",
"the",
"specified",
"resource",
"from",
"JIRA",
"unless",
"the",
"resource",
"is",
"already",
"expanded",
"and",
"the",
"optional",
"force",
"reload",
"flag",
"is",
"not",
"set"
] |
25e896f227ab81c528e9678708cb546d2f62f018
|
https://github.com/sumoheavy/jira-ruby/blob/25e896f227ab81c528e9678708cb546d2f62f018/lib/jira/base.rb#L332-L337
|
12,173
|
sumoheavy/jira-ruby
|
lib/jira/base.rb
|
JIRA.Base.set_attrs_from_response
|
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
|
ruby
|
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
|
[
"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.
|
[
"Sets",
"the",
"attributes",
"hash",
"from",
"a",
"HTTPResponse",
"object",
"from",
"JIRA",
"if",
"it",
"is",
"not",
"nil",
"or",
"is",
"not",
"a",
"json",
"response",
"."
] |
25e896f227ab81c528e9678708cb546d2f62f018
|
https://github.com/sumoheavy/jira-ruby/blob/25e896f227ab81c528e9678708cb546d2f62f018/lib/jira/base.rb#L380-L385
|
12,174
|
sumoheavy/jira-ruby
|
lib/jira/base.rb
|
JIRA.Base.set_attrs
|
def set_attrs(hash, clobber = true, target = nil)
target ||= @attrs
if clobber
target.merge!(hash)
hash
else
hash.each do |k, v|
if v.is_a?(Hash)
set_attrs(v, clobber, target[k])
else
target[k] = v
end
end
end
end
|
ruby
|
def set_attrs(hash, clobber = true, target = nil)
target ||= @attrs
if clobber
target.merge!(hash)
hash
else
hash.each do |k, v|
if v.is_a?(Hash)
set_attrs(v, clobber, target[k])
else
target[k] = v
end
end
end
end
|
[
"def",
"set_attrs",
"(",
"hash",
",",
"clobber",
"=",
"true",
",",
"target",
"=",
"nil",
")",
"target",
"||=",
"@attrs",
"if",
"clobber",
"target",
".",
"merge!",
"(",
"hash",
")",
"hash",
"else",
"hash",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"if",
"v",
".",
"is_a?",
"(",
"Hash",
")",
"set_attrs",
"(",
"v",
",",
"clobber",
",",
"target",
"[",
"k",
"]",
")",
"else",
"target",
"[",
"k",
"]",
"=",
"v",
"end",
"end",
"end",
"end"
] |
Set the current attributes from a hash. If clobber is true, any existing
hash values will be clobbered by the new hash, otherwise the hash will
be deeply merged into attrs. The target paramater is for internal use only
and should not be used.
|
[
"Set",
"the",
"current",
"attributes",
"from",
"a",
"hash",
".",
"If",
"clobber",
"is",
"true",
"any",
"existing",
"hash",
"values",
"will",
"be",
"clobbered",
"by",
"the",
"new",
"hash",
"otherwise",
"the",
"hash",
"will",
"be",
"deeply",
"merged",
"into",
"attrs",
".",
"The",
"target",
"paramater",
"is",
"for",
"internal",
"use",
"only",
"and",
"should",
"not",
"be",
"used",
"."
] |
25e896f227ab81c528e9678708cb546d2f62f018
|
https://github.com/sumoheavy/jira-ruby/blob/25e896f227ab81c528e9678708cb546d2f62f018/lib/jira/base.rb#L391-L405
|
12,175
|
chanks/que
|
lib/que/job_methods.rb
|
Que.JobMethods._run
|
def _run(args: nil, reraise_errors: false)
if args.nil? && que_target
args = que_target.que_attrs.fetch(:args)
end
run(*args)
default_resolve_action if que_target && !que_target.que_resolved
rescue => error
raise error unless que_target
que_target.que_error = error
run_error_notifier =
begin
handle_error(error)
rescue => error_2
Que.notify_error(error_2, que_target.que_attrs)
true
end
Que.notify_error(error, que_target.que_attrs) if run_error_notifier
retry_in_default_interval unless que_target.que_resolved
raise error if reraise_errors
end
|
ruby
|
def _run(args: nil, reraise_errors: false)
if args.nil? && que_target
args = que_target.que_attrs.fetch(:args)
end
run(*args)
default_resolve_action if que_target && !que_target.que_resolved
rescue => error
raise error unless que_target
que_target.que_error = error
run_error_notifier =
begin
handle_error(error)
rescue => error_2
Que.notify_error(error_2, que_target.que_attrs)
true
end
Que.notify_error(error, que_target.que_attrs) if run_error_notifier
retry_in_default_interval unless que_target.que_resolved
raise error if reraise_errors
end
|
[
"def",
"_run",
"(",
"args",
":",
"nil",
",",
"reraise_errors",
":",
"false",
")",
"if",
"args",
".",
"nil?",
"&&",
"que_target",
"args",
"=",
"que_target",
".",
"que_attrs",
".",
"fetch",
"(",
":args",
")",
"end",
"run",
"(",
"args",
")",
"default_resolve_action",
"if",
"que_target",
"&&",
"!",
"que_target",
".",
"que_resolved",
"rescue",
"=>",
"error",
"raise",
"error",
"unless",
"que_target",
"que_target",
".",
"que_error",
"=",
"error",
"run_error_notifier",
"=",
"begin",
"handle_error",
"(",
"error",
")",
"rescue",
"=>",
"error_2",
"Que",
".",
"notify_error",
"(",
"error_2",
",",
"que_target",
".",
"que_attrs",
")",
"true",
"end",
"Que",
".",
"notify_error",
"(",
"error",
",",
"que_target",
".",
"que_attrs",
")",
"if",
"run_error_notifier",
"retry_in_default_interval",
"unless",
"que_target",
".",
"que_resolved",
"raise",
"error",
"if",
"reraise_errors",
"end"
] |
Note that we delegate almost all methods to the result of the que_target
method, which could be one of a few things, depending on the circumstance.
Run the job with error handling and cleanup logic. Optionally support
overriding the args, because it's necessary when jobs are invoked from
ActiveJob.
|
[
"Note",
"that",
"we",
"delegate",
"almost",
"all",
"methods",
"to",
"the",
"result",
"of",
"the",
"que_target",
"method",
"which",
"could",
"be",
"one",
"of",
"a",
"few",
"things",
"depending",
"on",
"the",
"circumstance",
".",
"Run",
"the",
"job",
"with",
"error",
"handling",
"and",
"cleanup",
"logic",
".",
"Optionally",
"support",
"overriding",
"the",
"args",
"because",
"it",
"s",
"necessary",
"when",
"jobs",
"are",
"invoked",
"from",
"ActiveJob",
"."
] |
c7ae049db0ca13056a28c71ae610f8900f21feb4
|
https://github.com/chanks/que/blob/c7ae049db0ca13056a28c71ae610f8900f21feb4/lib/que/job_methods.rb#L42-L66
|
12,176
|
chanks/que
|
lib/que/job_methods.rb
|
Que.JobMethods.handle_error
|
def handle_error(error)
return unless que_target
max = resolve_que_setting(:maximum_retry_count)
if max && error_count > max
expire
else
retry_in_default_interval
end
end
|
ruby
|
def handle_error(error)
return unless que_target
max = resolve_que_setting(:maximum_retry_count)
if max && error_count > max
expire
else
retry_in_default_interval
end
end
|
[
"def",
"handle_error",
"(",
"error",
")",
"return",
"unless",
"que_target",
"max",
"=",
"resolve_que_setting",
"(",
":maximum_retry_count",
")",
"if",
"max",
"&&",
"error_count",
">",
"max",
"expire",
"else",
"retry_in_default_interval",
"end",
"end"
] |
To be overridden in subclasses.
|
[
"To",
"be",
"overridden",
"in",
"subclasses",
"."
] |
c7ae049db0ca13056a28c71ae610f8900f21feb4
|
https://github.com/chanks/que/blob/c7ae049db0ca13056a28c71ae610f8900f21feb4/lib/que/job_methods.rb#L124-L134
|
12,177
|
chanks/que
|
lib/que/job_methods.rb
|
Que.JobMethods.retry_in
|
def retry_in(period)
return unless que_target
if id = que_target.que_attrs[:id]
values = [period]
if e = que_target.que_error
values << "#{e.class}: #{e.message}".slice(0, 500) << e.backtrace.join("\n").slice(0, 10000)
else
values << nil << nil
end
Que.execute :set_error, values << id
end
que_target.que_resolved = true
end
|
ruby
|
def retry_in(period)
return unless que_target
if id = que_target.que_attrs[:id]
values = [period]
if e = que_target.que_error
values << "#{e.class}: #{e.message}".slice(0, 500) << e.backtrace.join("\n").slice(0, 10000)
else
values << nil << nil
end
Que.execute :set_error, values << id
end
que_target.que_resolved = true
end
|
[
"def",
"retry_in",
"(",
"period",
")",
"return",
"unless",
"que_target",
"if",
"id",
"=",
"que_target",
".",
"que_attrs",
"[",
":id",
"]",
"values",
"=",
"[",
"period",
"]",
"if",
"e",
"=",
"que_target",
".",
"que_error",
"values",
"<<",
"\"#{e.class}: #{e.message}\"",
".",
"slice",
"(",
"0",
",",
"500",
")",
"<<",
"e",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\"",
")",
".",
"slice",
"(",
"0",
",",
"10000",
")",
"else",
"values",
"<<",
"nil",
"<<",
"nil",
"end",
"Que",
".",
"execute",
":set_error",
",",
"values",
"<<",
"id",
"end",
"que_target",
".",
"que_resolved",
"=",
"true",
"end"
] |
Explicitly check for the job id in these helpers, because it won't exist
if we're running synchronously.
|
[
"Explicitly",
"check",
"for",
"the",
"job",
"id",
"in",
"these",
"helpers",
"because",
"it",
"won",
"t",
"exist",
"if",
"we",
"re",
"running",
"synchronously",
"."
] |
c7ae049db0ca13056a28c71ae610f8900f21feb4
|
https://github.com/chanks/que/blob/c7ae049db0ca13056a28c71ae610f8900f21feb4/lib/que/job_methods.rb#L144-L160
|
12,178
|
chanks/que
|
lib/que/job_buffer.rb
|
Que.JobBuffer.push
|
def push(*metajobs)
Que.internal_log(:job_buffer_push, self) do
{
maximum_size: maximum_size,
ids: metajobs.map(&:id),
current_queue: to_a,
}
end
sync do
return metajobs if _stopping?
@array.concat(metajobs).sort!
# Relying on the hash's contents being sorted, here.
priority_queues.reverse_each do |_, pq|
pq.waiting_count.times do
job = _shift_job(pq.priority)
break if job.nil? # False would mean we're stopping.
pq.push(job)
end
end
# If we passed the maximum buffer size, drop the lowest sort keys and
# return their ids to be unlocked.
overage = -_buffer_space
pop(overage) if overage > 0
end
end
|
ruby
|
def push(*metajobs)
Que.internal_log(:job_buffer_push, self) do
{
maximum_size: maximum_size,
ids: metajobs.map(&:id),
current_queue: to_a,
}
end
sync do
return metajobs if _stopping?
@array.concat(metajobs).sort!
# Relying on the hash's contents being sorted, here.
priority_queues.reverse_each do |_, pq|
pq.waiting_count.times do
job = _shift_job(pq.priority)
break if job.nil? # False would mean we're stopping.
pq.push(job)
end
end
# If we passed the maximum buffer size, drop the lowest sort keys and
# return their ids to be unlocked.
overage = -_buffer_space
pop(overage) if overage > 0
end
end
|
[
"def",
"push",
"(",
"*",
"metajobs",
")",
"Que",
".",
"internal_log",
"(",
":job_buffer_push",
",",
"self",
")",
"do",
"{",
"maximum_size",
":",
"maximum_size",
",",
"ids",
":",
"metajobs",
".",
"map",
"(",
":id",
")",
",",
"current_queue",
":",
"to_a",
",",
"}",
"end",
"sync",
"do",
"return",
"metajobs",
"if",
"_stopping?",
"@array",
".",
"concat",
"(",
"metajobs",
")",
".",
"sort!",
"# Relying on the hash's contents being sorted, here.",
"priority_queues",
".",
"reverse_each",
"do",
"|",
"_",
",",
"pq",
"|",
"pq",
".",
"waiting_count",
".",
"times",
"do",
"job",
"=",
"_shift_job",
"(",
"pq",
".",
"priority",
")",
"break",
"if",
"job",
".",
"nil?",
"# False would mean we're stopping.",
"pq",
".",
"push",
"(",
"job",
")",
"end",
"end",
"# If we passed the maximum buffer size, drop the lowest sort keys and",
"# return their ids to be unlocked.",
"overage",
"=",
"-",
"_buffer_space",
"pop",
"(",
"overage",
")",
"if",
"overage",
">",
"0",
"end",
"end"
] |
Since we use a mutex, which is not reentrant, we have to be a little
careful to not call a method that locks the mutex when we've already
locked it. So, as a general rule, public methods handle locking the mutex
when necessary, while private methods handle the actual underlying data
changes. This lets us reuse those private methods without running into
locking issues.
|
[
"Since",
"we",
"use",
"a",
"mutex",
"which",
"is",
"not",
"reentrant",
"we",
"have",
"to",
"be",
"a",
"little",
"careful",
"to",
"not",
"call",
"a",
"method",
"that",
"locks",
"the",
"mutex",
"when",
"we",
"ve",
"already",
"locked",
"it",
".",
"So",
"as",
"a",
"general",
"rule",
"public",
"methods",
"handle",
"locking",
"the",
"mutex",
"when",
"necessary",
"while",
"private",
"methods",
"handle",
"the",
"actual",
"underlying",
"data",
"changes",
".",
"This",
"lets",
"us",
"reuse",
"those",
"private",
"methods",
"without",
"running",
"into",
"locking",
"issues",
"."
] |
c7ae049db0ca13056a28c71ae610f8900f21feb4
|
https://github.com/chanks/que/blob/c7ae049db0ca13056a28c71ae610f8900f21feb4/lib/que/job_buffer.rb#L46-L74
|
12,179
|
middleman/middleman
|
middleman-core/lib/middleman-core/dns_resolver.rb
|
Middleman.DnsResolver.ips_for
|
def ips_for(name)
resolvers.each do |r|
ips = r.getaddresses(name)
return ips unless ips.nil? || ips.empty?
end
[]
end
|
ruby
|
def ips_for(name)
resolvers.each do |r|
ips = r.getaddresses(name)
return ips unless ips.nil? || ips.empty?
end
[]
end
|
[
"def",
"ips_for",
"(",
"name",
")",
"resolvers",
".",
"each",
"do",
"|",
"r",
"|",
"ips",
"=",
"r",
".",
"getaddresses",
"(",
"name",
")",
"return",
"ips",
"unless",
"ips",
".",
"nil?",
"||",
"ips",
".",
"empty?",
"end",
"[",
"]",
"end"
] |
Get ips for given name
First the local resolver is used. On POSIX-systems /etc/hosts is used. On
Windows C:\Windows\System32\drivers\etc\hosts is used.
@param [String] name
The name which should be resolved.
|
[
"Get",
"ips",
"for",
"given",
"name"
] |
a0dd9f78094813162895511e8516e0c5507cee50
|
https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/dns_resolver.rb#L63-L71
|
12,180
|
middleman/middleman
|
middleman-core/lib/middleman-core/config_context.rb
|
Middleman.ConfigContext.mime_type
|
def mime_type(type, value)
type = ".#{type}" unless type.to_s[0] == '.'
::Rack::Mime::MIME_TYPES[type] = value
end
|
ruby
|
def mime_type(type, value)
type = ".#{type}" unless type.to_s[0] == '.'
::Rack::Mime::MIME_TYPES[type] = value
end
|
[
"def",
"mime_type",
"(",
"type",
",",
"value",
")",
"type",
"=",
"\".#{type}\"",
"unless",
"type",
".",
"to_s",
"[",
"0",
"]",
"==",
"'.'",
"::",
"Rack",
"::",
"Mime",
"::",
"MIME_TYPES",
"[",
"type",
"]",
"=",
"value",
"end"
] |
Add a new mime-type for a specific extension
@param [Symbol] type File extension
@param [String] value Mime type
@return [void]
|
[
"Add",
"a",
"new",
"mime",
"-",
"type",
"for",
"a",
"specific",
"extension"
] |
a0dd9f78094813162895511e8516e0c5507cee50
|
https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/config_context.rb#L62-L65
|
12,181
|
middleman/middleman
|
middleman-core/lib/middleman-core/extension_manager.rb
|
Middleman.ExtensionManager.activate
|
def activate(ext_name, options_hash = ::Middleman::EMPTY_HASH, &block)
begin
extension = ::Middleman::Extensions.load(ext_name)
rescue LoadError => e
logger.debug "== Failed Activation `#{ext_name}` : #{e.message}"
return
end
logger.debug "== Activating: #{ext_name}"
if extension.supports_multiple_instances?
@activated[ext_name] ||= {}
key = "instance_#{@activated[ext_name].keys.length}"
@activated[ext_name][key] = extension.new(@app, options_hash, &block)
elsif active?(ext_name)
raise "#{ext_name} has already been activated and cannot be re-activated."
else
@activated[ext_name] = extension.new(@app, options_hash, &block)
end
end
|
ruby
|
def activate(ext_name, options_hash = ::Middleman::EMPTY_HASH, &block)
begin
extension = ::Middleman::Extensions.load(ext_name)
rescue LoadError => e
logger.debug "== Failed Activation `#{ext_name}` : #{e.message}"
return
end
logger.debug "== Activating: #{ext_name}"
if extension.supports_multiple_instances?
@activated[ext_name] ||= {}
key = "instance_#{@activated[ext_name].keys.length}"
@activated[ext_name][key] = extension.new(@app, options_hash, &block)
elsif active?(ext_name)
raise "#{ext_name} has already been activated and cannot be re-activated."
else
@activated[ext_name] = extension.new(@app, options_hash, &block)
end
end
|
[
"def",
"activate",
"(",
"ext_name",
",",
"options_hash",
"=",
"::",
"Middleman",
"::",
"EMPTY_HASH",
",",
"&",
"block",
")",
"begin",
"extension",
"=",
"::",
"Middleman",
"::",
"Extensions",
".",
"load",
"(",
"ext_name",
")",
"rescue",
"LoadError",
"=>",
"e",
"logger",
".",
"debug",
"\"== Failed Activation `#{ext_name}` : #{e.message}\"",
"return",
"end",
"logger",
".",
"debug",
"\"== Activating: #{ext_name}\"",
"if",
"extension",
".",
"supports_multiple_instances?",
"@activated",
"[",
"ext_name",
"]",
"||=",
"{",
"}",
"key",
"=",
"\"instance_#{@activated[ext_name].keys.length}\"",
"@activated",
"[",
"ext_name",
"]",
"[",
"key",
"]",
"=",
"extension",
".",
"new",
"(",
"@app",
",",
"options_hash",
",",
"block",
")",
"elsif",
"active?",
"(",
"ext_name",
")",
"raise",
"\"#{ext_name} has already been activated and cannot be re-activated.\"",
"else",
"@activated",
"[",
"ext_name",
"]",
"=",
"extension",
".",
"new",
"(",
"@app",
",",
"options_hash",
",",
"block",
")",
"end",
"end"
] |
Activate an extension, optionally passing in options.
This method is typically used from a project's `config.rb`.
@example Activate an extension with no options
activate :lorem
@example Activate an extension, with options
activate :minify_javascript, inline: true
@example Use a block to configure extension options
activate :minify_javascript do |opts|
opts.ignore += ['*-test.js']
end
@param [Symbol] ext_name The name of thed extension to activate
@param [Hash] options Options to pass to the extension
@yield [Middleman::Configuration::ConfigurationManager] Extension options that can be modified before the extension is initialized.
@return [void]
|
[
"Activate",
"an",
"extension",
"optionally",
"passing",
"in",
"options",
".",
"This",
"method",
"is",
"typically",
"used",
"from",
"a",
"project",
"s",
"config",
".",
"rb",
"."
] |
a0dd9f78094813162895511e8516e0c5507cee50
|
https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/extension_manager.rb#L53-L72
|
12,182
|
middleman/middleman
|
middleman-core/lib/middleman-core/application.rb
|
Middleman.Application.apply_cli_options
|
def apply_cli_options
config[:cli_options].each do |k, v|
setting = config.setting(k.to_sym)
next unless setting
v = setting.options[:import].call(v) if setting.options[:import]
config[k.to_sym] = v
end
end
|
ruby
|
def apply_cli_options
config[:cli_options].each do |k, v|
setting = config.setting(k.to_sym)
next unless setting
v = setting.options[:import].call(v) if setting.options[:import]
config[k.to_sym] = v
end
end
|
[
"def",
"apply_cli_options",
"config",
"[",
":cli_options",
"]",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"setting",
"=",
"config",
".",
"setting",
"(",
"k",
".",
"to_sym",
")",
"next",
"unless",
"setting",
"v",
"=",
"setting",
".",
"options",
"[",
":import",
"]",
".",
"call",
"(",
"v",
")",
"if",
"setting",
".",
"options",
"[",
":import",
"]",
"config",
"[",
"k",
".",
"to_sym",
"]",
"=",
"v",
"end",
"end"
] |
Initialize the Middleman project
|
[
"Initialize",
"the",
"Middleman",
"project"
] |
a0dd9f78094813162895511e8516e0c5507cee50
|
https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/application.rb#L309-L318
|
12,183
|
middleman/middleman
|
middleman-core/lib/middleman-core/application.rb
|
Middleman.Application.prune_tilt_templates!
|
def prune_tilt_templates!
mapping = ::Tilt.default_mapping
mapping.lazy_map.each_key do |key|
begin
mapping[key]
rescue LoadError, NameError
end
end
mapping.lazy_map.clear
end
|
ruby
|
def prune_tilt_templates!
mapping = ::Tilt.default_mapping
mapping.lazy_map.each_key do |key|
begin
mapping[key]
rescue LoadError, NameError
end
end
mapping.lazy_map.clear
end
|
[
"def",
"prune_tilt_templates!",
"mapping",
"=",
"::",
"Tilt",
".",
"default_mapping",
"mapping",
".",
"lazy_map",
".",
"each_key",
"do",
"|",
"key",
"|",
"begin",
"mapping",
"[",
"key",
"]",
"rescue",
"LoadError",
",",
"NameError",
"end",
"end",
"mapping",
".",
"lazy_map",
".",
"clear",
"end"
] |
Clean up missing Tilt exts
|
[
"Clean",
"up",
"missing",
"Tilt",
"exts"
] |
a0dd9f78094813162895511e8516e0c5507cee50
|
https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/application.rb#L344-L353
|
12,184
|
middleman/middleman
|
middleman-cli/lib/middleman-cli/extension.rb
|
Middleman::Cli.Extension.extension
|
def extension
copy_file 'extension/gitignore', File.join(name, '.gitignore') unless options[:'skip-git']
template 'extension/Rakefile', File.join(name, 'Rakefile')
template 'extension/gemspec', File.join(name, "#{name}.gemspec")
template 'extension/Gemfile', File.join(name, 'Gemfile')
template 'extension/lib/lib.rb', File.join(name, 'lib', "#{name}.rb")
template 'extension/lib/lib/extension.rb', File.join(name, 'lib', name, 'extension.rb')
template 'extension/features/support/env.rb', File.join(name, 'features', 'support', 'env.rb')
empty_directory File.join(name, 'fixtures')
end
|
ruby
|
def extension
copy_file 'extension/gitignore', File.join(name, '.gitignore') unless options[:'skip-git']
template 'extension/Rakefile', File.join(name, 'Rakefile')
template 'extension/gemspec', File.join(name, "#{name}.gemspec")
template 'extension/Gemfile', File.join(name, 'Gemfile')
template 'extension/lib/lib.rb', File.join(name, 'lib', "#{name}.rb")
template 'extension/lib/lib/extension.rb', File.join(name, 'lib', name, 'extension.rb')
template 'extension/features/support/env.rb', File.join(name, 'features', 'support', 'env.rb')
empty_directory File.join(name, 'fixtures')
end
|
[
"def",
"extension",
"copy_file",
"'extension/gitignore'",
",",
"File",
".",
"join",
"(",
"name",
",",
"'.gitignore'",
")",
"unless",
"options",
"[",
":'",
"'",
"]",
"template",
"'extension/Rakefile'",
",",
"File",
".",
"join",
"(",
"name",
",",
"'Rakefile'",
")",
"template",
"'extension/gemspec'",
",",
"File",
".",
"join",
"(",
"name",
",",
"\"#{name}.gemspec\"",
")",
"template",
"'extension/Gemfile'",
",",
"File",
".",
"join",
"(",
"name",
",",
"'Gemfile'",
")",
"template",
"'extension/lib/lib.rb'",
",",
"File",
".",
"join",
"(",
"name",
",",
"'lib'",
",",
"\"#{name}.rb\"",
")",
"template",
"'extension/lib/lib/extension.rb'",
",",
"File",
".",
"join",
"(",
"name",
",",
"'lib'",
",",
"name",
",",
"'extension.rb'",
")",
"template",
"'extension/features/support/env.rb'",
",",
"File",
".",
"join",
"(",
"name",
",",
"'features'",
",",
"'support'",
",",
"'env.rb'",
")",
"empty_directory",
"File",
".",
"join",
"(",
"name",
",",
"'fixtures'",
")",
"end"
] |
The extension task
|
[
"The",
"extension",
"task"
] |
a0dd9f78094813162895511e8516e0c5507cee50
|
https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-cli/lib/middleman-cli/extension.rb#L27-L36
|
12,185
|
middleman/middleman
|
middleman-core/lib/middleman-core/extension.rb
|
Middleman.Extension.add_exposed_to_context
|
def add_exposed_to_context(context)
(self.class.exposed_to_template || {}).each do |k, v|
context.define_singleton_method(k, &method(v))
end
end
|
ruby
|
def add_exposed_to_context(context)
(self.class.exposed_to_template || {}).each do |k, v|
context.define_singleton_method(k, &method(v))
end
end
|
[
"def",
"add_exposed_to_context",
"(",
"context",
")",
"(",
"self",
".",
"class",
".",
"exposed_to_template",
"||",
"{",
"}",
")",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"context",
".",
"define_singleton_method",
"(",
"k",
",",
"method",
"(",
"v",
")",
")",
"end",
"end"
] |
Extensions are instantiated when they are activated.
@param [Middleman::Application] app The Middleman::Application instance
@param [Hash] options_hash The raw options hash. Subclasses should not manipulate this directly - it will be turned into {#options}.
@yield An optional block that can be used to customize options before the extension is activated.
@yieldparam [Middleman::Configuration::ConfigurationManager] options Extension options
@!method before_configuration
Respond to the `before_configuration` event.
If a `before_configuration` method is implemented, that method will be run before `config.rb` is run.
@note Because most extensions are activated from within `config.rb`, they *will not run* any `before_configuration` hook.
@!method after_configuration
Respond to the `after_configuration` event.
If an `after_configuration` method is implemented, that method will be run before `config.rb` is run.
@!method before_build
Respond to the `before_build` event.
If an `before_build` method is implemented, that method will be run before the builder runs.
@!method after_build
Respond to the `after_build` event.
If an `after_build` method is implemented, that method will be run after the builder runs.
@!method ready
Respond to the `ready` event.
If an `ready` method is implemented, that method will be run after the app has finished booting up.
@!method manipulate_resource_list(resources)
Manipulate the resource list by transforming or adding {Sitemap::Resource}s.
Sitemap manipulation is a powerful way of interacting with a project, since it can modify each {Sitemap::Resource} or generate new {Sitemap::Resources}. This method is used in a pipeline where each sitemap manipulator is run in turn, with each one being fed the output of the previous manipulator. See the source of built-in Middleman extensions like {Middleman::Extensions::DirectoryIndexes} and {Middleman::Extensions::AssetHash} for examples of how to use this.
@note This method *must* return the full set of resources, because its return value will be used as the new sitemap.
@see http://middlemanapp.com/advanced/sitemap/ Sitemap Documentation
@see Sitemap::Store
@see Sitemap::Resource
@param [Array<Sitemap::Resource>] resources A list of all the resources known to the sitemap.
@return [Array<Sitemap::Resource>] The transformed list of resources.
|
[
"Extensions",
"are",
"instantiated",
"when",
"they",
"are",
"activated",
"."
] |
a0dd9f78094813162895511e8516e0c5507cee50
|
https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/extension.rb#L355-L359
|
12,186
|
middleman/middleman
|
middleman-cli/lib/middleman-cli/init.rb
|
Middleman::Cli.Init.init
|
def init
require 'fileutils'
require 'tmpdir'
unless git_present?
msg = 'You need to install the git command line tool to initialize a new project. '
msg << "For help installing git, please refer to GitHub's tutorial at https://help.github.com/articles/set-up-git"
say msg, :red
exit 1
end
repo_path, repo_branch = if shortname?(options[:template])
require 'open-uri'
require 'json'
api = 'https://directory.middlemanapp.com/api'
uri = ::URI.parse("#{api}/#{options[:template]}.json")
begin
data = ::JSON.parse(uri.read)
is_local_dir = false
data['links']['github'].split('#')
rescue ::OpenURI::HTTPError
say "Template `#{options[:template]}` not found in Middleman Directory."
say 'Did you mean to use a full `user/repo` path?'
exit 1
end
else
repo_name, repo_branch = options[:template].split('#')
repo_path, is_local_dir = repository_path(repo_name)
[repo_path, repo_branch]
end
begin
dir = is_local_dir ? repo_path : clone_repository(repo_path, repo_branch)
inside(target) do
thorfile = File.join(dir, 'Thorfile')
if File.exist?(thorfile)
::Thor::Util.load_thorfile(thorfile)
invoke 'middleman:generator'
else
source_paths << dir
directory dir, '.', exclude_pattern: /\.git\/|\.gitignore$/
end
bundle_args = options[:'bundle-path'] ? " --path=#{options[:'bundle-path']}" : ''
run("bundle install#{bundle_args}") unless ENV['TEST'] || options[:'skip-bundle']
end
ensure
FileUtils.remove_entry(dir) if !is_local_dir && File.directory?(dir)
end
end
|
ruby
|
def init
require 'fileutils'
require 'tmpdir'
unless git_present?
msg = 'You need to install the git command line tool to initialize a new project. '
msg << "For help installing git, please refer to GitHub's tutorial at https://help.github.com/articles/set-up-git"
say msg, :red
exit 1
end
repo_path, repo_branch = if shortname?(options[:template])
require 'open-uri'
require 'json'
api = 'https://directory.middlemanapp.com/api'
uri = ::URI.parse("#{api}/#{options[:template]}.json")
begin
data = ::JSON.parse(uri.read)
is_local_dir = false
data['links']['github'].split('#')
rescue ::OpenURI::HTTPError
say "Template `#{options[:template]}` not found in Middleman Directory."
say 'Did you mean to use a full `user/repo` path?'
exit 1
end
else
repo_name, repo_branch = options[:template].split('#')
repo_path, is_local_dir = repository_path(repo_name)
[repo_path, repo_branch]
end
begin
dir = is_local_dir ? repo_path : clone_repository(repo_path, repo_branch)
inside(target) do
thorfile = File.join(dir, 'Thorfile')
if File.exist?(thorfile)
::Thor::Util.load_thorfile(thorfile)
invoke 'middleman:generator'
else
source_paths << dir
directory dir, '.', exclude_pattern: /\.git\/|\.gitignore$/
end
bundle_args = options[:'bundle-path'] ? " --path=#{options[:'bundle-path']}" : ''
run("bundle install#{bundle_args}") unless ENV['TEST'] || options[:'skip-bundle']
end
ensure
FileUtils.remove_entry(dir) if !is_local_dir && File.directory?(dir)
end
end
|
[
"def",
"init",
"require",
"'fileutils'",
"require",
"'tmpdir'",
"unless",
"git_present?",
"msg",
"=",
"'You need to install the git command line tool to initialize a new project. '",
"msg",
"<<",
"\"For help installing git, please refer to GitHub's tutorial at https://help.github.com/articles/set-up-git\"",
"say",
"msg",
",",
":red",
"exit",
"1",
"end",
"repo_path",
",",
"repo_branch",
"=",
"if",
"shortname?",
"(",
"options",
"[",
":template",
"]",
")",
"require",
"'open-uri'",
"require",
"'json'",
"api",
"=",
"'https://directory.middlemanapp.com/api'",
"uri",
"=",
"::",
"URI",
".",
"parse",
"(",
"\"#{api}/#{options[:template]}.json\"",
")",
"begin",
"data",
"=",
"::",
"JSON",
".",
"parse",
"(",
"uri",
".",
"read",
")",
"is_local_dir",
"=",
"false",
"data",
"[",
"'links'",
"]",
"[",
"'github'",
"]",
".",
"split",
"(",
"'#'",
")",
"rescue",
"::",
"OpenURI",
"::",
"HTTPError",
"say",
"\"Template `#{options[:template]}` not found in Middleman Directory.\"",
"say",
"'Did you mean to use a full `user/repo` path?'",
"exit",
"1",
"end",
"else",
"repo_name",
",",
"repo_branch",
"=",
"options",
"[",
":template",
"]",
".",
"split",
"(",
"'#'",
")",
"repo_path",
",",
"is_local_dir",
"=",
"repository_path",
"(",
"repo_name",
")",
"[",
"repo_path",
",",
"repo_branch",
"]",
"end",
"begin",
"dir",
"=",
"is_local_dir",
"?",
"repo_path",
":",
"clone_repository",
"(",
"repo_path",
",",
"repo_branch",
")",
"inside",
"(",
"target",
")",
"do",
"thorfile",
"=",
"File",
".",
"join",
"(",
"dir",
",",
"'Thorfile'",
")",
"if",
"File",
".",
"exist?",
"(",
"thorfile",
")",
"::",
"Thor",
"::",
"Util",
".",
"load_thorfile",
"(",
"thorfile",
")",
"invoke",
"'middleman:generator'",
"else",
"source_paths",
"<<",
"dir",
"directory",
"dir",
",",
"'.'",
",",
"exclude_pattern",
":",
"/",
"\\.",
"\\/",
"\\.",
"/",
"end",
"bundle_args",
"=",
"options",
"[",
":'",
"'",
"]",
"?",
"\" --path=#{options[:'bundle-path']}\"",
":",
"''",
"run",
"(",
"\"bundle install#{bundle_args}\"",
")",
"unless",
"ENV",
"[",
"'TEST'",
"]",
"||",
"options",
"[",
":'",
"'",
"]",
"end",
"ensure",
"FileUtils",
".",
"remove_entry",
"(",
"dir",
")",
"if",
"!",
"is_local_dir",
"&&",
"File",
".",
"directory?",
"(",
"dir",
")",
"end",
"end"
] |
The init task
|
[
"The",
"init",
"task"
] |
a0dd9f78094813162895511e8516e0c5507cee50
|
https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-cli/lib/middleman-cli/init.rb#L30-L84
|
12,187
|
middleman/middleman
|
middleman-cli/lib/middleman-cli/init.rb
|
Middleman::Cli.Init.which
|
def which(executable)
if File.file?(executable) && File.executable?(executable)
executable
elsif ENV['PATH']
path = ENV['PATH'].split(File::PATH_SEPARATOR).find do |p|
abs_path = File.join(p, executable)
File.file?(abs_path) && File.executable?(abs_path)
end
path && File.expand_path(executable, path)
end
end
|
ruby
|
def which(executable)
if File.file?(executable) && File.executable?(executable)
executable
elsif ENV['PATH']
path = ENV['PATH'].split(File::PATH_SEPARATOR).find do |p|
abs_path = File.join(p, executable)
File.file?(abs_path) && File.executable?(abs_path)
end
path && File.expand_path(executable, path)
end
end
|
[
"def",
"which",
"(",
"executable",
")",
"if",
"File",
".",
"file?",
"(",
"executable",
")",
"&&",
"File",
".",
"executable?",
"(",
"executable",
")",
"executable",
"elsif",
"ENV",
"[",
"'PATH'",
"]",
"path",
"=",
"ENV",
"[",
"'PATH'",
"]",
".",
"split",
"(",
"File",
"::",
"PATH_SEPARATOR",
")",
".",
"find",
"do",
"|",
"p",
"|",
"abs_path",
"=",
"File",
".",
"join",
"(",
"p",
",",
"executable",
")",
"File",
".",
"file?",
"(",
"abs_path",
")",
"&&",
"File",
".",
"executable?",
"(",
"abs_path",
")",
"end",
"path",
"&&",
"File",
".",
"expand_path",
"(",
"executable",
",",
"path",
")",
"end",
"end"
] |
Copied from Bundler
|
[
"Copied",
"from",
"Bundler"
] |
a0dd9f78094813162895511e8516e0c5507cee50
|
https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-cli/lib/middleman-cli/init.rb#L96-L106
|
12,188
|
middleman/middleman
|
middleman-cli/lib/middleman-cli/build.rb
|
Middleman::Cli.Build.build
|
def build
root = ENV['MM_ROOT'] || Dir.pwd
raise Thor::Error, 'Error: Could not find a Middleman project config, perhaps you are in the wrong folder?' unless File.exist?(File.join(root, 'config.rb'))
require 'middleman-core'
require 'middleman-core/logger'
require 'middleman-core/builder'
require 'fileutils'
verbose = options['verbose'] ? 0 : 1
instrument = options['instrument']
builder = nil
cli_options = options
::Middleman::Logger.singleton(verbose, instrument)
::Middleman::Util.instrument 'builder.setup' do
missing_and_changed = !options['only_changed'] && options['missing_and_changed']
should_track_dependencies = options['only_changed'] || missing_and_changed || options['track_dependencies']
data_collection_depth = options['data_collection_depth']
@app = ::Middleman::Application.new do
config[:mode] = :build
config[:show_exceptions] = false
config[:cli_options] = cli_options.each_with_object({}) do |(k, v), sum|
sum[k] = v
end
config[:track_data_access] = should_track_dependencies
config[:data_collection_depth] = data_collection_depth
end
builder = Middleman::Builder.new(@app,
glob: options['glob'],
dry_run: options['dry_run'],
clean: options['clean'],
parallel: options['parallel'],
only_changed: options['only_changed'],
missing_and_changed: missing_and_changed,
track_dependencies: should_track_dependencies,
visualize_graph: options['visualize_graph'])
builder.thor = self
builder.on_build_event(&method(:on_event))
end
::Middleman::Util.instrument 'builder.run' do
if builder.run!
clean_directories! if options['clean']
puts 'Project built successfully.'
else
msg = 'There were errors during this build'
msg << ', re-run with `middleman build --verbose` to see the full exception.' unless options['verbose']
shell.say msg, :red
exit(1)
end
end
end
|
ruby
|
def build
root = ENV['MM_ROOT'] || Dir.pwd
raise Thor::Error, 'Error: Could not find a Middleman project config, perhaps you are in the wrong folder?' unless File.exist?(File.join(root, 'config.rb'))
require 'middleman-core'
require 'middleman-core/logger'
require 'middleman-core/builder'
require 'fileutils'
verbose = options['verbose'] ? 0 : 1
instrument = options['instrument']
builder = nil
cli_options = options
::Middleman::Logger.singleton(verbose, instrument)
::Middleman::Util.instrument 'builder.setup' do
missing_and_changed = !options['only_changed'] && options['missing_and_changed']
should_track_dependencies = options['only_changed'] || missing_and_changed || options['track_dependencies']
data_collection_depth = options['data_collection_depth']
@app = ::Middleman::Application.new do
config[:mode] = :build
config[:show_exceptions] = false
config[:cli_options] = cli_options.each_with_object({}) do |(k, v), sum|
sum[k] = v
end
config[:track_data_access] = should_track_dependencies
config[:data_collection_depth] = data_collection_depth
end
builder = Middleman::Builder.new(@app,
glob: options['glob'],
dry_run: options['dry_run'],
clean: options['clean'],
parallel: options['parallel'],
only_changed: options['only_changed'],
missing_and_changed: missing_and_changed,
track_dependencies: should_track_dependencies,
visualize_graph: options['visualize_graph'])
builder.thor = self
builder.on_build_event(&method(:on_event))
end
::Middleman::Util.instrument 'builder.run' do
if builder.run!
clean_directories! if options['clean']
puts 'Project built successfully.'
else
msg = 'There were errors during this build'
msg << ', re-run with `middleman build --verbose` to see the full exception.' unless options['verbose']
shell.say msg, :red
exit(1)
end
end
end
|
[
"def",
"build",
"root",
"=",
"ENV",
"[",
"'MM_ROOT'",
"]",
"||",
"Dir",
".",
"pwd",
"raise",
"Thor",
"::",
"Error",
",",
"'Error: Could not find a Middleman project config, perhaps you are in the wrong folder?'",
"unless",
"File",
".",
"exist?",
"(",
"File",
".",
"join",
"(",
"root",
",",
"'config.rb'",
")",
")",
"require",
"'middleman-core'",
"require",
"'middleman-core/logger'",
"require",
"'middleman-core/builder'",
"require",
"'fileutils'",
"verbose",
"=",
"options",
"[",
"'verbose'",
"]",
"?",
"0",
":",
"1",
"instrument",
"=",
"options",
"[",
"'instrument'",
"]",
"builder",
"=",
"nil",
"cli_options",
"=",
"options",
"::",
"Middleman",
"::",
"Logger",
".",
"singleton",
"(",
"verbose",
",",
"instrument",
")",
"::",
"Middleman",
"::",
"Util",
".",
"instrument",
"'builder.setup'",
"do",
"missing_and_changed",
"=",
"!",
"options",
"[",
"'only_changed'",
"]",
"&&",
"options",
"[",
"'missing_and_changed'",
"]",
"should_track_dependencies",
"=",
"options",
"[",
"'only_changed'",
"]",
"||",
"missing_and_changed",
"||",
"options",
"[",
"'track_dependencies'",
"]",
"data_collection_depth",
"=",
"options",
"[",
"'data_collection_depth'",
"]",
"@app",
"=",
"::",
"Middleman",
"::",
"Application",
".",
"new",
"do",
"config",
"[",
":mode",
"]",
"=",
":build",
"config",
"[",
":show_exceptions",
"]",
"=",
"false",
"config",
"[",
":cli_options",
"]",
"=",
"cli_options",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"(",
"k",
",",
"v",
")",
",",
"sum",
"|",
"sum",
"[",
"k",
"]",
"=",
"v",
"end",
"config",
"[",
":track_data_access",
"]",
"=",
"should_track_dependencies",
"config",
"[",
":data_collection_depth",
"]",
"=",
"data_collection_depth",
"end",
"builder",
"=",
"Middleman",
"::",
"Builder",
".",
"new",
"(",
"@app",
",",
"glob",
":",
"options",
"[",
"'glob'",
"]",
",",
"dry_run",
":",
"options",
"[",
"'dry_run'",
"]",
",",
"clean",
":",
"options",
"[",
"'clean'",
"]",
",",
"parallel",
":",
"options",
"[",
"'parallel'",
"]",
",",
"only_changed",
":",
"options",
"[",
"'only_changed'",
"]",
",",
"missing_and_changed",
":",
"missing_and_changed",
",",
"track_dependencies",
":",
"should_track_dependencies",
",",
"visualize_graph",
":",
"options",
"[",
"'visualize_graph'",
"]",
")",
"builder",
".",
"thor",
"=",
"self",
"builder",
".",
"on_build_event",
"(",
"method",
"(",
":on_event",
")",
")",
"end",
"::",
"Middleman",
"::",
"Util",
".",
"instrument",
"'builder.run'",
"do",
"if",
"builder",
".",
"run!",
"clean_directories!",
"if",
"options",
"[",
"'clean'",
"]",
"puts",
"'Project built successfully.'",
"else",
"msg",
"=",
"'There were errors during this build'",
"msg",
"<<",
"', re-run with `middleman build --verbose` to see the full exception.'",
"unless",
"options",
"[",
"'verbose'",
"]",
"shell",
".",
"say",
"msg",
",",
":red",
"exit",
"(",
"1",
")",
"end",
"end",
"end"
] |
Core build Thor command
@return [void]
|
[
"Core",
"build",
"Thor",
"command"
] |
a0dd9f78094813162895511e8516e0c5507cee50
|
https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-cli/lib/middleman-cli/build.rb#L72-L130
|
12,189
|
middleman/middleman
|
middleman-cli/lib/middleman-cli/build.rb
|
Middleman::Cli.Build.on_event
|
def on_event(event_type, target, extra = nil)
case event_type
when :error
say_status :error, target, :red
shell.say extra, :red if options['verbose'] || options['bail']
raise 'Build error' if options['bail']
when :deleted
say_status :remove, target, :green
when :created
say_status :create, target, :green
when :identical
say_status :identical, target, :blue
when :skipped
say_status :skipped, target, :blue
when :updated
say_status :updated, target, :yellow
else
say_status event_type, extra, :blue
end
end
|
ruby
|
def on_event(event_type, target, extra = nil)
case event_type
when :error
say_status :error, target, :red
shell.say extra, :red if options['verbose'] || options['bail']
raise 'Build error' if options['bail']
when :deleted
say_status :remove, target, :green
when :created
say_status :create, target, :green
when :identical
say_status :identical, target, :blue
when :skipped
say_status :skipped, target, :blue
when :updated
say_status :updated, target, :yellow
else
say_status event_type, extra, :blue
end
end
|
[
"def",
"on_event",
"(",
"event_type",
",",
"target",
",",
"extra",
"=",
"nil",
")",
"case",
"event_type",
"when",
":error",
"say_status",
":error",
",",
"target",
",",
":red",
"shell",
".",
"say",
"extra",
",",
":red",
"if",
"options",
"[",
"'verbose'",
"]",
"||",
"options",
"[",
"'bail'",
"]",
"raise",
"'Build error'",
"if",
"options",
"[",
"'bail'",
"]",
"when",
":deleted",
"say_status",
":remove",
",",
"target",
",",
":green",
"when",
":created",
"say_status",
":create",
",",
"target",
",",
":green",
"when",
":identical",
"say_status",
":identical",
",",
"target",
",",
":blue",
"when",
":skipped",
"say_status",
":skipped",
",",
"target",
",",
":blue",
"when",
":updated",
"say_status",
":updated",
",",
"target",
",",
":yellow",
"else",
"say_status",
"event_type",
",",
"extra",
",",
":blue",
"end",
"end"
] |
Handles incoming events from the builder.
@param [Symbol] event_type The type of event.
@param [String] target The event contents.
@param [String] extra The extra information.
@return [void]
|
[
"Handles",
"incoming",
"events",
"from",
"the",
"builder",
"."
] |
a0dd9f78094813162895511e8516e0c5507cee50
|
https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-cli/lib/middleman-cli/build.rb#L139-L159
|
12,190
|
middleman/middleman
|
middleman-cli/lib/middleman-cli/build.rb
|
Middleman::Cli.Build.clean_directories!
|
def clean_directories!
all_build_files = File.join(@app.config[:build_dir], '**', '*')
empty_directories = Dir[all_build_files].select do |d|
File.directory?(d)
end
empty_directories.each do |d|
remove_file d, force: true if Pathname(d).children.empty?
end
end
|
ruby
|
def clean_directories!
all_build_files = File.join(@app.config[:build_dir], '**', '*')
empty_directories = Dir[all_build_files].select do |d|
File.directory?(d)
end
empty_directories.each do |d|
remove_file d, force: true if Pathname(d).children.empty?
end
end
|
[
"def",
"clean_directories!",
"all_build_files",
"=",
"File",
".",
"join",
"(",
"@app",
".",
"config",
"[",
":build_dir",
"]",
",",
"'**'",
",",
"'*'",
")",
"empty_directories",
"=",
"Dir",
"[",
"all_build_files",
"]",
".",
"select",
"do",
"|",
"d",
"|",
"File",
".",
"directory?",
"(",
"d",
")",
"end",
"empty_directories",
".",
"each",
"do",
"|",
"d",
"|",
"remove_file",
"d",
",",
"force",
":",
"true",
"if",
"Pathname",
"(",
"d",
")",
".",
"children",
".",
"empty?",
"end",
"end"
] |
Find empty directories in the build folder and remove them.
@return [Boolean]
|
[
"Find",
"empty",
"directories",
"in",
"the",
"build",
"folder",
"and",
"remove",
"them",
"."
] |
a0dd9f78094813162895511e8516e0c5507cee50
|
https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-cli/lib/middleman-cli/build.rb#L163-L173
|
12,191
|
middleman/middleman
|
middleman-core/lib/middleman-core/rack.rb
|
Middleman.Rack.process_request
|
def process_request(env, req, res)
start_time = Time.now
request_path = URI.decode(env['PATH_INFO'].dup)
request_path.force_encoding('UTF-8') if request_path.respond_to? :force_encoding
request_path = ::Middleman::Util.full_path(request_path, @middleman)
full_request_path = File.join(env['SCRIPT_NAME'], request_path) # Path including rack mount
# Get the resource object for this path
resource = @middleman.sitemap.by_destination_path(request_path.gsub(' ', '%20'))
# Return 404 if not in sitemap
return not_found(res, full_request_path) unless resource && !resource.ignored?
# If this path is a binary file, send it immediately
return send_file(resource, env) if resource.binary? || resource.static_file?
res['Content-Type'] = resource.content_type || 'text/plain'
begin
# Write out the contents of the page
res.write resource.render({}, rack: { request: req })
# Valid content is a 200 status
res.status = 200
rescue Middleman::TemplateRenderer::TemplateNotFound => e
res.write "Error: #{e.message}"
res.status = 500
end
# End the request
logger.debug "== Finishing Request: #{resource.destination_path} (#{(Time.now - start_time).round(2)}s)"
halt res.finish
end
|
ruby
|
def process_request(env, req, res)
start_time = Time.now
request_path = URI.decode(env['PATH_INFO'].dup)
request_path.force_encoding('UTF-8') if request_path.respond_to? :force_encoding
request_path = ::Middleman::Util.full_path(request_path, @middleman)
full_request_path = File.join(env['SCRIPT_NAME'], request_path) # Path including rack mount
# Get the resource object for this path
resource = @middleman.sitemap.by_destination_path(request_path.gsub(' ', '%20'))
# Return 404 if not in sitemap
return not_found(res, full_request_path) unless resource && !resource.ignored?
# If this path is a binary file, send it immediately
return send_file(resource, env) if resource.binary? || resource.static_file?
res['Content-Type'] = resource.content_type || 'text/plain'
begin
# Write out the contents of the page
res.write resource.render({}, rack: { request: req })
# Valid content is a 200 status
res.status = 200
rescue Middleman::TemplateRenderer::TemplateNotFound => e
res.write "Error: #{e.message}"
res.status = 500
end
# End the request
logger.debug "== Finishing Request: #{resource.destination_path} (#{(Time.now - start_time).round(2)}s)"
halt res.finish
end
|
[
"def",
"process_request",
"(",
"env",
",",
"req",
",",
"res",
")",
"start_time",
"=",
"Time",
".",
"now",
"request_path",
"=",
"URI",
".",
"decode",
"(",
"env",
"[",
"'PATH_INFO'",
"]",
".",
"dup",
")",
"request_path",
".",
"force_encoding",
"(",
"'UTF-8'",
")",
"if",
"request_path",
".",
"respond_to?",
":force_encoding",
"request_path",
"=",
"::",
"Middleman",
"::",
"Util",
".",
"full_path",
"(",
"request_path",
",",
"@middleman",
")",
"full_request_path",
"=",
"File",
".",
"join",
"(",
"env",
"[",
"'SCRIPT_NAME'",
"]",
",",
"request_path",
")",
"# Path including rack mount",
"# Get the resource object for this path",
"resource",
"=",
"@middleman",
".",
"sitemap",
".",
"by_destination_path",
"(",
"request_path",
".",
"gsub",
"(",
"' '",
",",
"'%20'",
")",
")",
"# Return 404 if not in sitemap",
"return",
"not_found",
"(",
"res",
",",
"full_request_path",
")",
"unless",
"resource",
"&&",
"!",
"resource",
".",
"ignored?",
"# If this path is a binary file, send it immediately",
"return",
"send_file",
"(",
"resource",
",",
"env",
")",
"if",
"resource",
".",
"binary?",
"||",
"resource",
".",
"static_file?",
"res",
"[",
"'Content-Type'",
"]",
"=",
"resource",
".",
"content_type",
"||",
"'text/plain'",
"begin",
"# Write out the contents of the page",
"res",
".",
"write",
"resource",
".",
"render",
"(",
"{",
"}",
",",
"rack",
":",
"{",
"request",
":",
"req",
"}",
")",
"# Valid content is a 200 status",
"res",
".",
"status",
"=",
"200",
"rescue",
"Middleman",
"::",
"TemplateRenderer",
"::",
"TemplateNotFound",
"=>",
"e",
"res",
".",
"write",
"\"Error: #{e.message}\"",
"res",
".",
"status",
"=",
"500",
"end",
"# End the request",
"logger",
".",
"debug",
"\"== Finishing Request: #{resource.destination_path} (#{(Time.now - start_time).round(2)}s)\"",
"halt",
"res",
".",
"finish",
"end"
] |
Core response method. We process the request, check with
the sitemap, and return the correct file, response or status
message.
@param env
@param [Rack::Request] req
@param [Rack::Response] res
|
[
"Core",
"response",
"method",
".",
"We",
"process",
"the",
"request",
"check",
"with",
"the",
"sitemap",
"and",
"return",
"the",
"correct",
"file",
"response",
"or",
"status",
"message",
"."
] |
a0dd9f78094813162895511e8516e0c5507cee50
|
https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/rack.rb#L86-L119
|
12,192
|
middleman/middleman
|
middleman-core/lib/middleman-core/rack.rb
|
Middleman.Rack.not_found
|
def not_found(res, path)
path = ::Rack::Utils.escape_html(path)
res.status = 404
res.write "<html><head></head><body><h1>File Not Found</h1><p>#{path}</p></body></html>"
res.finish
end
|
ruby
|
def not_found(res, path)
path = ::Rack::Utils.escape_html(path)
res.status = 404
res.write "<html><head></head><body><h1>File Not Found</h1><p>#{path}</p></body></html>"
res.finish
end
|
[
"def",
"not_found",
"(",
"res",
",",
"path",
")",
"path",
"=",
"::",
"Rack",
"::",
"Utils",
".",
"escape_html",
"(",
"path",
")",
"res",
".",
"status",
"=",
"404",
"res",
".",
"write",
"\"<html><head></head><body><h1>File Not Found</h1><p>#{path}</p></body></html>\"",
"res",
".",
"finish",
"end"
] |
Halt request and return 404
|
[
"Halt",
"request",
"and",
"return",
"404"
] |
a0dd9f78094813162895511e8516e0c5507cee50
|
https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/rack.rb#L122-L127
|
12,193
|
middleman/middleman
|
middleman-core/lib/middleman-core/rack.rb
|
Middleman.Rack.send_file
|
def send_file(resource, env)
file = ::Rack::File.new nil
path = resource.file_descriptor[:full_path]
if !file.respond_to?(:path=)
request = ::Rack::Request.new(env)
response = file.serving(request, path)
else
file.path = path
response = file.serving(env)
end
status = response[0]
response[1]['Content-Encoding'] = 'gzip' if %w[.svgz .gz].include?(resource.ext)
# Do not set Content-Type if status is 1xx, 204, 205 or 304, otherwise
# Rack will throw an error (500)
if !(100..199).cover?(status) && ![204, 205, 304].include?(status)
response[1]['Content-Type'] = resource.content_type || (resource.binary? ? 'application/octet-stream' : 'text/plain')
end
halt response
end
|
ruby
|
def send_file(resource, env)
file = ::Rack::File.new nil
path = resource.file_descriptor[:full_path]
if !file.respond_to?(:path=)
request = ::Rack::Request.new(env)
response = file.serving(request, path)
else
file.path = path
response = file.serving(env)
end
status = response[0]
response[1]['Content-Encoding'] = 'gzip' if %w[.svgz .gz].include?(resource.ext)
# Do not set Content-Type if status is 1xx, 204, 205 or 304, otherwise
# Rack will throw an error (500)
if !(100..199).cover?(status) && ![204, 205, 304].include?(status)
response[1]['Content-Type'] = resource.content_type || (resource.binary? ? 'application/octet-stream' : 'text/plain')
end
halt response
end
|
[
"def",
"send_file",
"(",
"resource",
",",
"env",
")",
"file",
"=",
"::",
"Rack",
"::",
"File",
".",
"new",
"nil",
"path",
"=",
"resource",
".",
"file_descriptor",
"[",
":full_path",
"]",
"if",
"!",
"file",
".",
"respond_to?",
"(",
":path=",
")",
"request",
"=",
"::",
"Rack",
"::",
"Request",
".",
"new",
"(",
"env",
")",
"response",
"=",
"file",
".",
"serving",
"(",
"request",
",",
"path",
")",
"else",
"file",
".",
"path",
"=",
"path",
"response",
"=",
"file",
".",
"serving",
"(",
"env",
")",
"end",
"status",
"=",
"response",
"[",
"0",
"]",
"response",
"[",
"1",
"]",
"[",
"'Content-Encoding'",
"]",
"=",
"'gzip'",
"if",
"%w[",
".svgz",
".gz",
"]",
".",
"include?",
"(",
"resource",
".",
"ext",
")",
"# Do not set Content-Type if status is 1xx, 204, 205 or 304, otherwise",
"# Rack will throw an error (500)",
"if",
"!",
"(",
"100",
"..",
"199",
")",
".",
"cover?",
"(",
"status",
")",
"&&",
"!",
"[",
"204",
",",
"205",
",",
"304",
"]",
".",
"include?",
"(",
"status",
")",
"response",
"[",
"1",
"]",
"[",
"'Content-Type'",
"]",
"=",
"resource",
".",
"content_type",
"||",
"(",
"resource",
".",
"binary?",
"?",
"'application/octet-stream'",
":",
"'text/plain'",
")",
"end",
"halt",
"response",
"end"
] |
Immediately send static file
|
[
"Immediately",
"send",
"static",
"file"
] |
a0dd9f78094813162895511e8516e0c5507cee50
|
https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/rack.rb#L130-L149
|
12,194
|
middleman/middleman
|
middleman-cli/lib/middleman-cli/server.rb
|
Middleman::Cli.Server.server
|
def server
require 'middleman-core'
require 'middleman-core/preview_server'
unless ENV['MM_ROOT']
puts '== Could not find a Middleman project config.rb'
exit
end
params = {
debug: options['verbose'],
instrumenting: options['instrument'],
reload_paths: options['reload_paths'],
daemon: options['daemon']
}
puts '== The Middleman is loading'
::Middleman::PreviewServer.start(params, options)
end
|
ruby
|
def server
require 'middleman-core'
require 'middleman-core/preview_server'
unless ENV['MM_ROOT']
puts '== Could not find a Middleman project config.rb'
exit
end
params = {
debug: options['verbose'],
instrumenting: options['instrument'],
reload_paths: options['reload_paths'],
daemon: options['daemon']
}
puts '== The Middleman is loading'
::Middleman::PreviewServer.start(params, options)
end
|
[
"def",
"server",
"require",
"'middleman-core'",
"require",
"'middleman-core/preview_server'",
"unless",
"ENV",
"[",
"'MM_ROOT'",
"]",
"puts",
"'== Could not find a Middleman project config.rb'",
"exit",
"end",
"params",
"=",
"{",
"debug",
":",
"options",
"[",
"'verbose'",
"]",
",",
"instrumenting",
":",
"options",
"[",
"'instrument'",
"]",
",",
"reload_paths",
":",
"options",
"[",
"'reload_paths'",
"]",
",",
"daemon",
":",
"options",
"[",
"'daemon'",
"]",
"}",
"puts",
"'== The Middleman is loading'",
"::",
"Middleman",
"::",
"PreviewServer",
".",
"start",
"(",
"params",
",",
"options",
")",
"end"
] |
Start the server
|
[
"Start",
"the",
"server"
] |
a0dd9f78094813162895511e8516e0c5507cee50
|
https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-cli/lib/middleman-cli/server.rb#L36-L54
|
12,195
|
middleman/middleman
|
middleman-core/lib/middleman-core/template_context.rb
|
Middleman.TemplateContext.wrap_layout
|
def wrap_layout(layout_name, &block)
# Save current buffer for later
buf_was = save_buffer
# Find a layout for this file
layout_file = ::Middleman::TemplateRenderer.locate_layout(@app, layout_name, current_engine)
# Get the layout engine
extension = File.extname(layout_file[:relative_path])
engine = extension[1..-1].to_sym
# Store last engine for later (could be inside nested renders)
self.current_engine = engine
engine_was = current_engine
# By default, no content is captured
content = ''
# Attempt to capture HTML from block
begin
content = capture_html(&block) if block_given?
ensure
# Reset stored buffer, regardless of success
restore_buffer(buf_was)
end
@vertices <<= ::Middleman::Dependencies::FileVertex.from_source_file(@app, layout_file)
# Render the layout, with the contents of the block inside.
concat_safe_content render_file(layout_file, @locs, @opts) { content }
ensure
# Reset engine back to template's value, regardless of success
self.current_engine = engine_was
end
|
ruby
|
def wrap_layout(layout_name, &block)
# Save current buffer for later
buf_was = save_buffer
# Find a layout for this file
layout_file = ::Middleman::TemplateRenderer.locate_layout(@app, layout_name, current_engine)
# Get the layout engine
extension = File.extname(layout_file[:relative_path])
engine = extension[1..-1].to_sym
# Store last engine for later (could be inside nested renders)
self.current_engine = engine
engine_was = current_engine
# By default, no content is captured
content = ''
# Attempt to capture HTML from block
begin
content = capture_html(&block) if block_given?
ensure
# Reset stored buffer, regardless of success
restore_buffer(buf_was)
end
@vertices <<= ::Middleman::Dependencies::FileVertex.from_source_file(@app, layout_file)
# Render the layout, with the contents of the block inside.
concat_safe_content render_file(layout_file, @locs, @opts) { content }
ensure
# Reset engine back to template's value, regardless of success
self.current_engine = engine_was
end
|
[
"def",
"wrap_layout",
"(",
"layout_name",
",",
"&",
"block",
")",
"# Save current buffer for later",
"buf_was",
"=",
"save_buffer",
"# Find a layout for this file",
"layout_file",
"=",
"::",
"Middleman",
"::",
"TemplateRenderer",
".",
"locate_layout",
"(",
"@app",
",",
"layout_name",
",",
"current_engine",
")",
"# Get the layout engine",
"extension",
"=",
"File",
".",
"extname",
"(",
"layout_file",
"[",
":relative_path",
"]",
")",
"engine",
"=",
"extension",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"to_sym",
"# Store last engine for later (could be inside nested renders)",
"self",
".",
"current_engine",
"=",
"engine",
"engine_was",
"=",
"current_engine",
"# By default, no content is captured",
"content",
"=",
"''",
"# Attempt to capture HTML from block",
"begin",
"content",
"=",
"capture_html",
"(",
"block",
")",
"if",
"block_given?",
"ensure",
"# Reset stored buffer, regardless of success",
"restore_buffer",
"(",
"buf_was",
")",
"end",
"@vertices",
"<<=",
"::",
"Middleman",
"::",
"Dependencies",
"::",
"FileVertex",
".",
"from_source_file",
"(",
"@app",
",",
"layout_file",
")",
"# Render the layout, with the contents of the block inside.",
"concat_safe_content",
"render_file",
"(",
"layout_file",
",",
"@locs",
",",
"@opts",
")",
"{",
"content",
"}",
"ensure",
"# Reset engine back to template's value, regardless of success",
"self",
".",
"current_engine",
"=",
"engine_was",
"end"
] |
Allow layouts to be wrapped in the contents of other layouts.
@param [String, Symbol] layout_name
@return [void]
|
[
"Allow",
"layouts",
"to",
"be",
"wrapped",
"in",
"the",
"contents",
"of",
"other",
"layouts",
"."
] |
a0dd9f78094813162895511e8516e0c5507cee50
|
https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/template_context.rb#L81-L114
|
12,196
|
middleman/middleman
|
middleman-core/lib/middleman-core/template_context.rb
|
Middleman.TemplateContext.render_file
|
def render_file(file, locs, opts, &block)
_render_with_all_renderers(file[:relative_path].to_s, locs, self, opts, &block)
end
|
ruby
|
def render_file(file, locs, opts, &block)
_render_with_all_renderers(file[:relative_path].to_s, locs, self, opts, &block)
end
|
[
"def",
"render_file",
"(",
"file",
",",
"locs",
",",
"opts",
",",
"&",
"block",
")",
"_render_with_all_renderers",
"(",
"file",
"[",
":relative_path",
"]",
".",
"to_s",
",",
"locs",
",",
"self",
",",
"opts",
",",
"block",
")",
"end"
] |
Render a path with locs, opts and contents block.
@api private
@param [Middleman::SourceFile] file The file.
@param [Hash] locs Template locals.
@param [Hash] opts Template options.
@param [Proc] block A block will be evaluated to return internal contents.
@return [String] The resulting content string.
Contract IsA['Middleman::SourceFile'], Hash, Hash, Maybe[Proc] => String
|
[
"Render",
"a",
"path",
"with",
"locs",
"opts",
"and",
"contents",
"block",
"."
] |
a0dd9f78094813162895511e8516e0c5507cee50
|
https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/template_context.rb#L218-L220
|
12,197
|
middleman/middleman
|
middleman-core/lib/middleman-core/util/files.rb
|
Middleman.Util.glob_directory
|
def glob_directory(path)
results = ::Dir[path]
return results unless RUBY_PLATFORM =~ /darwin/
results.map { |r| r.encode('UTF-8', 'UTF-8-MAC') }
end
|
ruby
|
def glob_directory(path)
results = ::Dir[path]
return results unless RUBY_PLATFORM =~ /darwin/
results.map { |r| r.encode('UTF-8', 'UTF-8-MAC') }
end
|
[
"def",
"glob_directory",
"(",
"path",
")",
"results",
"=",
"::",
"Dir",
"[",
"path",
"]",
"return",
"results",
"unless",
"RUBY_PLATFORM",
"=~",
"/",
"/",
"results",
".",
"map",
"{",
"|",
"r",
"|",
"r",
".",
"encode",
"(",
"'UTF-8'",
",",
"'UTF-8-MAC'",
")",
"}",
"end"
] |
Glob a directory and try to keep path encoding consistent.
@param [String] path The glob path.
@return [Array<String>]
|
[
"Glob",
"a",
"directory",
"and",
"try",
"to",
"keep",
"path",
"encoding",
"consistent",
"."
] |
a0dd9f78094813162895511e8516e0c5507cee50
|
https://github.com/middleman/middleman/blob/a0dd9f78094813162895511e8516e0c5507cee50/middleman-core/lib/middleman-core/util/files.rb#L40-L46
|
12,198
|
razorpay/razorpay-ruby
|
lib/razorpay/request.rb
|
Razorpay.Request.create_instance
|
def create_instance(res)
response = res.parsed_response
# if there was an error, throw it
raise_error(response['error'], res.code) if response.nil? || response.key?('error')
# There must be a top level entity
# This is either one of payment, refund, or collection at present
begin
class_name = response['entity'].split('_').collect(&:capitalize).join
klass = Razorpay.const_get class_name
rescue NameError
# Use Entity class if we don't find any
klass = Razorpay::Entity
end
klass.new(response)
end
|
ruby
|
def create_instance(res)
response = res.parsed_response
# if there was an error, throw it
raise_error(response['error'], res.code) if response.nil? || response.key?('error')
# There must be a top level entity
# This is either one of payment, refund, or collection at present
begin
class_name = response['entity'].split('_').collect(&:capitalize).join
klass = Razorpay.const_get class_name
rescue NameError
# Use Entity class if we don't find any
klass = Razorpay::Entity
end
klass.new(response)
end
|
[
"def",
"create_instance",
"(",
"res",
")",
"response",
"=",
"res",
".",
"parsed_response",
"# if there was an error, throw it",
"raise_error",
"(",
"response",
"[",
"'error'",
"]",
",",
"res",
".",
"code",
")",
"if",
"response",
".",
"nil?",
"||",
"response",
".",
"key?",
"(",
"'error'",
")",
"# There must be a top level entity",
"# This is either one of payment, refund, or collection at present",
"begin",
"class_name",
"=",
"response",
"[",
"'entity'",
"]",
".",
"split",
"(",
"'_'",
")",
".",
"collect",
"(",
":capitalize",
")",
".",
"join",
"klass",
"=",
"Razorpay",
".",
"const_get",
"class_name",
"rescue",
"NameError",
"# Use Entity class if we don't find any",
"klass",
"=",
"Razorpay",
"::",
"Entity",
"end",
"klass",
".",
"new",
"(",
"response",
")",
"end"
] |
Recursively builds entity instances
out of all hashes in the response object
|
[
"Recursively",
"builds",
"entity",
"instances",
"out",
"of",
"all",
"hashes",
"in",
"the",
"response",
"object"
] |
2ef2a200e70fb7034c212673569cbba378a2ced6
|
https://github.com/razorpay/razorpay-ruby/blob/2ef2a200e70fb7034c212673569cbba378a2ced6/lib/razorpay/request.rb#L80-L97
|
12,199
|
attr-encrypted/attr_encrypted
|
lib/attr_encrypted.rb
|
AttrEncrypted.InstanceMethods.decrypt
|
def decrypt(attribute, encrypted_value)
encrypted_attributes[attribute.to_sym][:operation] = :decrypting
encrypted_attributes[attribute.to_sym][:value_present] = self.class.not_empty?(encrypted_value)
self.class.decrypt(attribute, encrypted_value, evaluated_attr_encrypted_options_for(attribute))
end
|
ruby
|
def decrypt(attribute, encrypted_value)
encrypted_attributes[attribute.to_sym][:operation] = :decrypting
encrypted_attributes[attribute.to_sym][:value_present] = self.class.not_empty?(encrypted_value)
self.class.decrypt(attribute, encrypted_value, evaluated_attr_encrypted_options_for(attribute))
end
|
[
"def",
"decrypt",
"(",
"attribute",
",",
"encrypted_value",
")",
"encrypted_attributes",
"[",
"attribute",
".",
"to_sym",
"]",
"[",
":operation",
"]",
"=",
":decrypting",
"encrypted_attributes",
"[",
"attribute",
".",
"to_sym",
"]",
"[",
":value_present",
"]",
"=",
"self",
".",
"class",
".",
"not_empty?",
"(",
"encrypted_value",
")",
"self",
".",
"class",
".",
"decrypt",
"(",
"attribute",
",",
"encrypted_value",
",",
"evaluated_attr_encrypted_options_for",
"(",
"attribute",
")",
")",
"end"
] |
Decrypts a value for the attribute specified using options evaluated in the current object's scope
Example
class User
attr_accessor :secret_key
attr_encrypted :email, key: :secret_key
def initialize(secret_key)
self.secret_key = secret_key
end
end
@user = User.new('some-secret-key')
@user.decrypt(:email, 'SOME_ENCRYPTED_EMAIL_STRING')
|
[
"Decrypts",
"a",
"value",
"for",
"the",
"attribute",
"specified",
"using",
"options",
"evaluated",
"in",
"the",
"current",
"object",
"s",
"scope"
] |
11df93aef14c661dd0c03169d382a0412f93124e
|
https://github.com/attr-encrypted/attr_encrypted/blob/11df93aef14c661dd0c03169d382a0412f93124e/lib/attr_encrypted.rb#L328-L332
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.