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
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
2,500
ustasb/pandata
lib/pandata/parser.rb
Pandata.Parser.get_webnames_from_search
def get_webnames_from_search(html) user_links = Nokogiri::HTML(html).css('.user_name a') webnames = [] user_links.each do |link| webnames << link['webname'] end webnames end
ruby
def get_webnames_from_search(html) user_links = Nokogiri::HTML(html).css('.user_name a') webnames = [] user_links.each do |link| webnames << link['webname'] end webnames end
[ "def", "get_webnames_from_search", "(", "html", ")", "user_links", "=", "Nokogiri", "::", "HTML", "(", "html", ")", ".", "css", "(", "'.user_name a'", ")", "webnames", "=", "[", "]", "user_links", ".", "each", "do", "|", "link", "|", "webnames", "<<", "link", "[", "'webname'", "]", "end", "webnames", "end" ]
Get the webnames from a user ID search. @param html [String] @return [Array] array of webnames
[ "Get", "the", "webnames", "from", "a", "user", "ID", "search", "." ]
c75f83813171bc6149eca53ff310dedca1a7a1cb
https://github.com/ustasb/pandata/blob/c75f83813171bc6149eca53ff310dedca1a7a1cb/lib/pandata/parser.rb#L11-L20
2,501
ustasb/pandata
lib/pandata/parser.rb
Pandata.Parser.get_next_data_indices
def get_next_data_indices(html) # .js-more-link is found on mobile pages. show_more = Nokogiri::HTML(html).css('.show_more, .js-more-link')[0] if show_more next_indices = {} data_attributes = ['nextStartIndex', 'nextLikeStartIndex', 'nextThumbStartIndex'] data_attributes.each do |attr_name| attr = show_more.attributes['data-' + attr_name.downcase] next_indices[attr_name.to_sym] = attr.value.to_i if attr end next_indices else false end end
ruby
def get_next_data_indices(html) # .js-more-link is found on mobile pages. show_more = Nokogiri::HTML(html).css('.show_more, .js-more-link')[0] if show_more next_indices = {} data_attributes = ['nextStartIndex', 'nextLikeStartIndex', 'nextThumbStartIndex'] data_attributes.each do |attr_name| attr = show_more.attributes['data-' + attr_name.downcase] next_indices[attr_name.to_sym] = attr.value.to_i if attr end next_indices else false end end
[ "def", "get_next_data_indices", "(", "html", ")", "# .js-more-link is found on mobile pages.", "show_more", "=", "Nokogiri", "::", "HTML", "(", "html", ")", ".", "css", "(", "'.show_more, .js-more-link'", ")", "[", "0", "]", "if", "show_more", "next_indices", "=", "{", "}", "data_attributes", "=", "[", "'nextStartIndex'", ",", "'nextLikeStartIndex'", ",", "'nextThumbStartIndex'", "]", "data_attributes", ".", "each", "do", "|", "attr_name", "|", "attr", "=", "show_more", ".", "attributes", "[", "'data-'", "+", "attr_name", ".", "downcase", "]", "next_indices", "[", "attr_name", ".", "to_sym", "]", "=", "attr", ".", "value", ".", "to_i", "if", "attr", "end", "next_indices", "else", "false", "end", "end" ]
Get the query parameters necessary to get the next page of data from Pandora. @param html [String] @return [Hash, False]
[ "Get", "the", "query", "parameters", "necessary", "to", "get", "the", "next", "page", "of", "data", "from", "Pandora", "." ]
c75f83813171bc6149eca53ff310dedca1a7a1cb
https://github.com/ustasb/pandata/blob/c75f83813171bc6149eca53ff310dedca1a7a1cb/lib/pandata/parser.rb#L25-L41
2,502
ustasb/pandata
lib/pandata/parser.rb
Pandata.Parser.infobox_each_link
def infobox_each_link(html) Nokogiri::HTML(html).css('.infobox').each do |infobox| infobox_body = infobox.css('.infobox-body') title_link = infobox_body.css('h3 a').text.strip subtitle_link = infobox_body.css('p a').first subtitle_link = subtitle_link.text.strip if subtitle_link yield(title_link, subtitle_link) end end
ruby
def infobox_each_link(html) Nokogiri::HTML(html).css('.infobox').each do |infobox| infobox_body = infobox.css('.infobox-body') title_link = infobox_body.css('h3 a').text.strip subtitle_link = infobox_body.css('p a').first subtitle_link = subtitle_link.text.strip if subtitle_link yield(title_link, subtitle_link) end end
[ "def", "infobox_each_link", "(", "html", ")", "Nokogiri", "::", "HTML", "(", "html", ")", ".", "css", "(", "'.infobox'", ")", ".", "each", "do", "|", "infobox", "|", "infobox_body", "=", "infobox", ".", "css", "(", "'.infobox-body'", ")", "title_link", "=", "infobox_body", ".", "css", "(", "'h3 a'", ")", ".", "text", ".", "strip", "subtitle_link", "=", "infobox_body", ".", "css", "(", "'p a'", ")", ".", "first", "subtitle_link", "=", "subtitle_link", ".", "text", ".", "strip", "if", "subtitle_link", "yield", "(", "title_link", ",", "subtitle_link", ")", "end", "end" ]
Loops over each .infobox container and yields the title and subtitle. @param html [String]
[ "Loops", "over", "each", ".", "infobox", "container", "and", "yields", "the", "title", "and", "subtitle", "." ]
c75f83813171bc6149eca53ff310dedca1a7a1cb
https://github.com/ustasb/pandata/blob/c75f83813171bc6149eca53ff310dedca1a7a1cb/lib/pandata/parser.rb#L96-L106
2,503
ustasb/pandata
lib/pandata/parser.rb
Pandata.Parser.doublelink_each_link
def doublelink_each_link(html) Nokogiri::HTML(html).css('.double-link').each do |doublelink| title_link = doublelink.css('.media__bd__header').text.strip subtitle_link = doublelink.css('.media__bd__subheader').text.strip yield(title_link, subtitle_link) end end
ruby
def doublelink_each_link(html) Nokogiri::HTML(html).css('.double-link').each do |doublelink| title_link = doublelink.css('.media__bd__header').text.strip subtitle_link = doublelink.css('.media__bd__subheader').text.strip yield(title_link, subtitle_link) end end
[ "def", "doublelink_each_link", "(", "html", ")", "Nokogiri", "::", "HTML", "(", "html", ")", ".", "css", "(", "'.double-link'", ")", ".", "each", "do", "|", "doublelink", "|", "title_link", "=", "doublelink", ".", "css", "(", "'.media__bd__header'", ")", ".", "text", ".", "strip", "subtitle_link", "=", "doublelink", ".", "css", "(", "'.media__bd__subheader'", ")", ".", "text", ".", "strip", "yield", "(", "title_link", ",", "subtitle_link", ")", "end", "end" ]
Loops over each .double-link container and yields the title and subtitle. Encountered on mobile pages. @param html [String]
[ "Loops", "over", "each", ".", "double", "-", "link", "container", "and", "yields", "the", "title", "and", "subtitle", ".", "Encountered", "on", "mobile", "pages", "." ]
c75f83813171bc6149eca53ff310dedca1a7a1cb
https://github.com/ustasb/pandata/blob/c75f83813171bc6149eca53ff310dedca1a7a1cb/lib/pandata/parser.rb#L111-L118
2,504
ustasb/pandata
lib/pandata/parser.rb
Pandata.Parser.get_followx_users
def get_followx_users(html) users = [] Nokogiri::HTML(html).css('.follow_section').each do |section| listener_name = section.css('.listener_name').first webname = listener_name['webname'] # Remove any 'spans with a space' that sometimes appear with special characters. listener_name.css('span').each(&:remove) name = listener_name.text.strip href = section.css('a').first['href'] users << { name: name, webname: webname, href: href } end users end
ruby
def get_followx_users(html) users = [] Nokogiri::HTML(html).css('.follow_section').each do |section| listener_name = section.css('.listener_name').first webname = listener_name['webname'] # Remove any 'spans with a space' that sometimes appear with special characters. listener_name.css('span').each(&:remove) name = listener_name.text.strip href = section.css('a').first['href'] users << { name: name, webname: webname, href: href } end users end
[ "def", "get_followx_users", "(", "html", ")", "users", "=", "[", "]", "Nokogiri", "::", "HTML", "(", "html", ")", ".", "css", "(", "'.follow_section'", ")", ".", "each", "do", "|", "section", "|", "listener_name", "=", "section", ".", "css", "(", "'.listener_name'", ")", ".", "first", "webname", "=", "listener_name", "[", "'webname'", "]", "# Remove any 'spans with a space' that sometimes appear with special characters.", "listener_name", ".", "css", "(", "'span'", ")", ".", "each", "(", ":remove", ")", "name", "=", "listener_name", ".", "text", ".", "strip", "href", "=", "section", ".", "css", "(", "'a'", ")", ".", "first", "[", "'href'", "]", "users", "<<", "{", "name", ":", "name", ",", "webname", ":", "webname", ",", "href", ":", "href", "}", "end", "users", "end" ]
Loops over each .follow_section container. @param html [String] @return [Hash] with keys :name, :webname and :href
[ "Loops", "over", "each", ".", "follow_section", "container", "." ]
c75f83813171bc6149eca53ff310dedca1a7a1cb
https://github.com/ustasb/pandata/blob/c75f83813171bc6149eca53ff310dedca1a7a1cb/lib/pandata/parser.rb#L132-L149
2,505
piotrmurach/tty-platform
lib/tty/platform.rb
TTY.Platform.detect_system_properties
def detect_system_properties(arch) parts = (arch || architecture).split('-', 2) if parts.length == 1 @cpu, system = nil, parts.shift else @cpu, system = *parts end @os, @version = *find_os_and_version(system) [@cpu, @os, @version] end
ruby
def detect_system_properties(arch) parts = (arch || architecture).split('-', 2) if parts.length == 1 @cpu, system = nil, parts.shift else @cpu, system = *parts end @os, @version = *find_os_and_version(system) [@cpu, @os, @version] end
[ "def", "detect_system_properties", "(", "arch", ")", "parts", "=", "(", "arch", "||", "architecture", ")", ".", "split", "(", "'-'", ",", "2", ")", "if", "parts", ".", "length", "==", "1", "@cpu", ",", "system", "=", "nil", ",", "parts", ".", "shift", "else", "@cpu", ",", "system", "=", "parts", "end", "@os", ",", "@version", "=", "find_os_and_version", "(", "system", ")", "[", "@cpu", ",", "@os", ",", "@version", "]", "end" ]
Infer system properties from architecture information @return [Array[String, String String]] @api private
[ "Infer", "system", "properties", "from", "architecture", "information" ]
ef35579edc941e79b9bbe1ce3952b961088e2210
https://github.com/piotrmurach/tty-platform/blob/ef35579edc941e79b9bbe1ce3952b961088e2210/lib/tty/platform.rb#L104-L114
2,506
dennisreimann/masq
app/controllers/masq/server_controller.rb
Masq.ServerController.decide
def decide @site = current_account.sites.find_or_initialize_by_url(checkid_request.trust_root) @site.persona = current_account.personas.find(params[:persona_id] || :first) if sreg_request || ax_store_request || ax_fetch_request end
ruby
def decide @site = current_account.sites.find_or_initialize_by_url(checkid_request.trust_root) @site.persona = current_account.personas.find(params[:persona_id] || :first) if sreg_request || ax_store_request || ax_fetch_request end
[ "def", "decide", "@site", "=", "current_account", ".", "sites", ".", "find_or_initialize_by_url", "(", "checkid_request", ".", "trust_root", ")", "@site", ".", "persona", "=", "current_account", ".", "personas", ".", "find", "(", "params", "[", ":persona_id", "]", "||", ":first", ")", "if", "sreg_request", "||", "ax_store_request", "||", "ax_fetch_request", "end" ]
Displays the decision page on that the user can confirm the request and choose which data should be transfered to the relying party.
[ "Displays", "the", "decision", "page", "on", "that", "the", "user", "can", "confirm", "the", "request", "and", "choose", "which", "data", "should", "be", "transfered", "to", "the", "relying", "party", "." ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/controllers/masq/server_controller.rb#L64-L67
2,507
dennisreimann/masq
app/controllers/masq/server_controller.rb
Masq.ServerController.complete
def complete if params[:cancel] cancel else resp = checkid_request.answer(true, nil, identifier(current_account)) if params[:always] @site = current_account.sites.find_or_create_by_persona_id_and_url(params[:site][:persona_id], params[:site][:url]) @site.update_attributes(params[:site]) elsif sreg_request || ax_fetch_request @site = current_account.sites.find_or_initialize_by_persona_id_and_url(params[:site][:persona_id], params[:site][:url]) @site.attributes = params[:site] elsif ax_store_request @site = current_account.sites.find_or_initialize_by_persona_id_and_url(params[:site][:persona_id], params[:site][:url]) not_supported, not_accepted, accepted = [], [], [] ax_store_request.data.each do |type_uri, values| if property = Persona.attribute_name_for_type_uri(type_uri) store_attribute = params[:site][:ax_store][property.to_sym] if store_attribute && !store_attribute[:value].blank? @site.persona.update_attribute(property, values.first) accepted << type_uri else not_accepted << type_uri end else not_supported << type_uri end end ax_store_response = (accepted.count > 0) ? OpenID::AX::StoreResponse.new : OpenID::AX::StoreResponse.new(false, "None of the attributes were accepted.") resp.add_extension(ax_store_response) end resp = add_pape(resp, auth_policies, auth_level, auth_time) resp = add_sreg(resp, @site.sreg_properties) if sreg_request && @site.sreg_properties resp = add_ax(resp, @site.ax_properties) if ax_fetch_request && @site.ax_properties render_response(resp) end end
ruby
def complete if params[:cancel] cancel else resp = checkid_request.answer(true, nil, identifier(current_account)) if params[:always] @site = current_account.sites.find_or_create_by_persona_id_and_url(params[:site][:persona_id], params[:site][:url]) @site.update_attributes(params[:site]) elsif sreg_request || ax_fetch_request @site = current_account.sites.find_or_initialize_by_persona_id_and_url(params[:site][:persona_id], params[:site][:url]) @site.attributes = params[:site] elsif ax_store_request @site = current_account.sites.find_or_initialize_by_persona_id_and_url(params[:site][:persona_id], params[:site][:url]) not_supported, not_accepted, accepted = [], [], [] ax_store_request.data.each do |type_uri, values| if property = Persona.attribute_name_for_type_uri(type_uri) store_attribute = params[:site][:ax_store][property.to_sym] if store_attribute && !store_attribute[:value].blank? @site.persona.update_attribute(property, values.first) accepted << type_uri else not_accepted << type_uri end else not_supported << type_uri end end ax_store_response = (accepted.count > 0) ? OpenID::AX::StoreResponse.new : OpenID::AX::StoreResponse.new(false, "None of the attributes were accepted.") resp.add_extension(ax_store_response) end resp = add_pape(resp, auth_policies, auth_level, auth_time) resp = add_sreg(resp, @site.sreg_properties) if sreg_request && @site.sreg_properties resp = add_ax(resp, @site.ax_properties) if ax_fetch_request && @site.ax_properties render_response(resp) end end
[ "def", "complete", "if", "params", "[", ":cancel", "]", "cancel", "else", "resp", "=", "checkid_request", ".", "answer", "(", "true", ",", "nil", ",", "identifier", "(", "current_account", ")", ")", "if", "params", "[", ":always", "]", "@site", "=", "current_account", ".", "sites", ".", "find_or_create_by_persona_id_and_url", "(", "params", "[", ":site", "]", "[", ":persona_id", "]", ",", "params", "[", ":site", "]", "[", ":url", "]", ")", "@site", ".", "update_attributes", "(", "params", "[", ":site", "]", ")", "elsif", "sreg_request", "||", "ax_fetch_request", "@site", "=", "current_account", ".", "sites", ".", "find_or_initialize_by_persona_id_and_url", "(", "params", "[", ":site", "]", "[", ":persona_id", "]", ",", "params", "[", ":site", "]", "[", ":url", "]", ")", "@site", ".", "attributes", "=", "params", "[", ":site", "]", "elsif", "ax_store_request", "@site", "=", "current_account", ".", "sites", ".", "find_or_initialize_by_persona_id_and_url", "(", "params", "[", ":site", "]", "[", ":persona_id", "]", ",", "params", "[", ":site", "]", "[", ":url", "]", ")", "not_supported", ",", "not_accepted", ",", "accepted", "=", "[", "]", ",", "[", "]", ",", "[", "]", "ax_store_request", ".", "data", ".", "each", "do", "|", "type_uri", ",", "values", "|", "if", "property", "=", "Persona", ".", "attribute_name_for_type_uri", "(", "type_uri", ")", "store_attribute", "=", "params", "[", ":site", "]", "[", ":ax_store", "]", "[", "property", ".", "to_sym", "]", "if", "store_attribute", "&&", "!", "store_attribute", "[", ":value", "]", ".", "blank?", "@site", ".", "persona", ".", "update_attribute", "(", "property", ",", "values", ".", "first", ")", "accepted", "<<", "type_uri", "else", "not_accepted", "<<", "type_uri", "end", "else", "not_supported", "<<", "type_uri", "end", "end", "ax_store_response", "=", "(", "accepted", ".", "count", ">", "0", ")", "?", "OpenID", "::", "AX", "::", "StoreResponse", ".", "new", ":", "OpenID", "::", "AX", "::", "StoreResponse", ".", "new", "(", "false", ",", "\"None of the attributes were accepted.\"", ")", "resp", ".", "add_extension", "(", "ax_store_response", ")", "end", "resp", "=", "add_pape", "(", "resp", ",", "auth_policies", ",", "auth_level", ",", "auth_time", ")", "resp", "=", "add_sreg", "(", "resp", ",", "@site", ".", "sreg_properties", ")", "if", "sreg_request", "&&", "@site", ".", "sreg_properties", "resp", "=", "add_ax", "(", "resp", ",", "@site", ".", "ax_properties", ")", "if", "ax_fetch_request", "&&", "@site", ".", "ax_properties", "render_response", "(", "resp", ")", "end", "end" ]
This action is called by submitting the decision form, the information entered by the user is used to answer the request. If the user decides to always trust the relying party, a new site according to the release policies the will be created.
[ "This", "action", "is", "called", "by", "submitting", "the", "decision", "form", "the", "information", "entered", "by", "the", "user", "is", "used", "to", "answer", "the", "request", ".", "If", "the", "user", "decides", "to", "always", "trust", "the", "relying", "party", "a", "new", "site", "according", "to", "the", "release", "policies", "the", "will", "be", "created", "." ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/controllers/masq/server_controller.rb#L72-L107
2,508
dennisreimann/masq
app/controllers/masq/server_controller.rb
Masq.ServerController.handle_checkid_request
def handle_checkid_request if allow_verification? save_checkid_request redirect_to proceed_path elsif openid_request.immediate render_response(openid_request.answer(false)) else reset_session request = save_checkid_request session[:return_to] = proceed_path redirect_to( request.from_trusted_domain? ? login_path : safe_login_path ) end end
ruby
def handle_checkid_request if allow_verification? save_checkid_request redirect_to proceed_path elsif openid_request.immediate render_response(openid_request.answer(false)) else reset_session request = save_checkid_request session[:return_to] = proceed_path redirect_to( request.from_trusted_domain? ? login_path : safe_login_path ) end end
[ "def", "handle_checkid_request", "if", "allow_verification?", "save_checkid_request", "redirect_to", "proceed_path", "elsif", "openid_request", ".", "immediate", "render_response", "(", "openid_request", ".", "answer", "(", "false", ")", ")", "else", "reset_session", "request", "=", "save_checkid_request", "session", "[", ":return_to", "]", "=", "proceed_path", "redirect_to", "(", "request", ".", "from_trusted_domain?", "?", "login_path", ":", "safe_login_path", ")", "end", "end" ]
Decides how to process an incoming checkid request. If the user is already logged in he will be forwarded to the proceed action. If the user is not logged in and the request is immediate, the request cannot be answered successfully. In case the user is not logged in, the request will be stored and the user is asked to log in.
[ "Decides", "how", "to", "process", "an", "incoming", "checkid", "request", ".", "If", "the", "user", "is", "already", "logged", "in", "he", "will", "be", "forwarded", "to", "the", "proceed", "action", ".", "If", "the", "user", "is", "not", "logged", "in", "and", "the", "request", "is", "immediate", "the", "request", "cannot", "be", "answered", "successfully", ".", "In", "case", "the", "user", "is", "not", "logged", "in", "the", "request", "will", "be", "stored", "and", "the", "user", "is", "asked", "to", "log", "in", "." ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/controllers/masq/server_controller.rb#L121-L133
2,509
dennisreimann/masq
app/controllers/masq/server_controller.rb
Masq.ServerController.save_checkid_request
def save_checkid_request clear_checkid_request request = OpenIdRequest.create!(:parameters => openid_params) session[:request_token] = request.token request end
ruby
def save_checkid_request clear_checkid_request request = OpenIdRequest.create!(:parameters => openid_params) session[:request_token] = request.token request end
[ "def", "save_checkid_request", "clear_checkid_request", "request", "=", "OpenIdRequest", ".", "create!", "(", ":parameters", "=>", "openid_params", ")", "session", "[", ":request_token", "]", "=", "request", ".", "token", "request", "end" ]
Stores the current OpenID request. Returns the OpenIdRequest
[ "Stores", "the", "current", "OpenID", "request", ".", "Returns", "the", "OpenIdRequest" ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/controllers/masq/server_controller.rb#L137-L143
2,510
dennisreimann/masq
app/controllers/masq/server_controller.rb
Masq.ServerController.ensure_valid_checkid_request
def ensure_valid_checkid_request self.openid_request = checkid_request if !openid_request.is_a?(OpenID::Server::CheckIDRequest) redirect_to root_path, :alert => t(:identity_verification_request_invalid) elsif !allow_verification? flash[:notice] = logged_in? && !pape_requirements_met?(auth_time) ? t(:service_provider_requires_reauthentication_last_login_too_long_ago) : t(:login_to_verify_identity) session[:return_to] = proceed_path redirect_to login_path end end
ruby
def ensure_valid_checkid_request self.openid_request = checkid_request if !openid_request.is_a?(OpenID::Server::CheckIDRequest) redirect_to root_path, :alert => t(:identity_verification_request_invalid) elsif !allow_verification? flash[:notice] = logged_in? && !pape_requirements_met?(auth_time) ? t(:service_provider_requires_reauthentication_last_login_too_long_ago) : t(:login_to_verify_identity) session[:return_to] = proceed_path redirect_to login_path end end
[ "def", "ensure_valid_checkid_request", "self", ".", "openid_request", "=", "checkid_request", "if", "!", "openid_request", ".", "is_a?", "(", "OpenID", "::", "Server", "::", "CheckIDRequest", ")", "redirect_to", "root_path", ",", ":alert", "=>", "t", "(", ":identity_verification_request_invalid", ")", "elsif", "!", "allow_verification?", "flash", "[", ":notice", "]", "=", "logged_in?", "&&", "!", "pape_requirements_met?", "(", "auth_time", ")", "?", "t", "(", ":service_provider_requires_reauthentication_last_login_too_long_ago", ")", ":", "t", "(", ":login_to_verify_identity", ")", "session", "[", ":return_to", "]", "=", "proceed_path", "redirect_to", "login_path", "end", "end" ]
Use this as before_filter for every CheckID request based action. Loads the current openid request and cancels if none can be found. The user has to log in, if he has not verified his ownership of the identifier, yet.
[ "Use", "this", "as", "before_filter", "for", "every", "CheckID", "request", "based", "action", ".", "Loads", "the", "current", "openid", "request", "and", "cancels", "if", "none", "can", "be", "found", ".", "The", "user", "has", "to", "log", "in", "if", "he", "has", "not", "verified", "his", "ownership", "of", "the", "identifier", "yet", "." ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/controllers/masq/server_controller.rb#L157-L168
2,511
dennisreimann/masq
app/controllers/masq/server_controller.rb
Masq.ServerController.transform_ax_data
def transform_ax_data(parameters) data = {} parameters.each_pair do |key, details| if details['value'] data["type.#{key}"] = details['type'] data["value.#{key}"] = details['value'] end end data end
ruby
def transform_ax_data(parameters) data = {} parameters.each_pair do |key, details| if details['value'] data["type.#{key}"] = details['type'] data["value.#{key}"] = details['value'] end end data end
[ "def", "transform_ax_data", "(", "parameters", ")", "data", "=", "{", "}", "parameters", ".", "each_pair", "do", "|", "key", ",", "details", "|", "if", "details", "[", "'value'", "]", "data", "[", "\"type.#{key}\"", "]", "=", "details", "[", "'type'", "]", "data", "[", "\"value.#{key}\"", "]", "=", "details", "[", "'value'", "]", "end", "end", "data", "end" ]
Transforms the parameters from the form to valid AX response values
[ "Transforms", "the", "parameters", "from", "the", "form", "to", "valid", "AX", "response", "values" ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/controllers/masq/server_controller.rb#L190-L199
2,512
dennisreimann/masq
app/controllers/masq/server_controller.rb
Masq.ServerController.render_openid_error
def render_openid_error(exception) error = case exception when OpenID::Server::MalformedTrustRoot then "Malformed trust root '#{exception.to_s}'" else exception.to_s end render :text => h("Invalid OpenID request: #{error}"), :status => 500 end
ruby
def render_openid_error(exception) error = case exception when OpenID::Server::MalformedTrustRoot then "Malformed trust root '#{exception.to_s}'" else exception.to_s end render :text => h("Invalid OpenID request: #{error}"), :status => 500 end
[ "def", "render_openid_error", "(", "exception", ")", "error", "=", "case", "exception", "when", "OpenID", "::", "Server", "::", "MalformedTrustRoot", "then", "\"Malformed trust root '#{exception.to_s}'\"", "else", "exception", ".", "to_s", "end", "render", ":text", "=>", "h", "(", "\"Invalid OpenID request: #{error}\"", ")", ",", ":status", "=>", "500", "end" ]
Renders the exception message as text output
[ "Renders", "the", "exception", "message", "as", "text", "output" ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/controllers/masq/server_controller.rb#L202-L208
2,513
mceachen/micro_magick
lib/micro_magick/image.rb
MicroMagick.Image.add_input_option
def add_input_option(option_name, *args) (@input_options ||= []).push(option_name) args.each { |ea| @input_options.push(Shellwords.escape(ea.to_s)) } # Support call chaining: self end
ruby
def add_input_option(option_name, *args) (@input_options ||= []).push(option_name) args.each { |ea| @input_options.push(Shellwords.escape(ea.to_s)) } # Support call chaining: self end
[ "def", "add_input_option", "(", "option_name", ",", "*", "args", ")", "(", "@input_options", "||=", "[", "]", ")", ".", "push", "(", "option_name", ")", "args", ".", "each", "{", "|", "ea", "|", "@input_options", ".", "push", "(", "Shellwords", ".", "escape", "(", "ea", ".", "to_s", ")", ")", "}", "# Support call chaining:", "self", "end" ]
If you need to add an option that affects processing of input files, you can use this method.
[ "If", "you", "need", "to", "add", "an", "option", "that", "affects", "processing", "of", "input", "files", "you", "can", "use", "this", "method", "." ]
c4b9259826f16295a561c83e6e084660f4f9229e
https://github.com/mceachen/micro_magick/blob/c4b9259826f16295a561c83e6e084660f4f9229e/lib/micro_magick/image.rb#L17-L23
2,514
mceachen/micro_magick
lib/micro_magick/image.rb
MicroMagick.Image.square_crop
def square_crop(gravity = 'Center') gravity(gravity) unless gravity.nil? d = [width, height].min crop("#{d}x#{d}+0+0!") end
ruby
def square_crop(gravity = 'Center') gravity(gravity) unless gravity.nil? d = [width, height].min crop("#{d}x#{d}+0+0!") end
[ "def", "square_crop", "(", "gravity", "=", "'Center'", ")", "gravity", "(", "gravity", ")", "unless", "gravity", ".", "nil?", "d", "=", "[", "width", ",", "height", "]", ".", "min", "crop", "(", "\"#{d}x#{d}+0+0!\"", ")", "end" ]
Crop to a square, using the specified gravity.
[ "Crop", "to", "a", "square", "using", "the", "specified", "gravity", "." ]
c4b9259826f16295a561c83e6e084660f4f9229e
https://github.com/mceachen/micro_magick/blob/c4b9259826f16295a561c83e6e084660f4f9229e/lib/micro_magick/image.rb#L55-L59
2,515
jhass/open_graph_reader
lib/open_graph_reader/base.rb
OpenGraphReader.Base.method_missing
def method_missing(method, *args, &block) name = method.to_s if respond_to_missing? name @bases[name] else super(method, *args, &block) end end
ruby
def method_missing(method, *args, &block) name = method.to_s if respond_to_missing? name @bases[name] else super(method, *args, &block) end end
[ "def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "name", "=", "method", ".", "to_s", "if", "respond_to_missing?", "name", "@bases", "[", "name", "]", "else", "super", "(", "method", ",", "args", ",", "block", ")", "end", "end" ]
Makes the found root objects available. @return [Object]
[ "Makes", "the", "found", "root", "objects", "available", "." ]
5488354b7dd75b5411a881d734aa7176546e7cb4
https://github.com/jhass/open_graph_reader/blob/5488354b7dd75b5411a881d734aa7176546e7cb4/lib/open_graph_reader/base.rb#L61-L68
2,516
tomharris/random_data
lib/random_data/locations.rb
RandomData.Locations.uk_post_code
def uk_post_code post_towns = %w(BM CB CV LE LI LS KT MK NE OX PL YO) # Can't remember any othes at the moment number_1 = rand(100).to_s number_2 = rand(100).to_s # Easier way to do this? letters = ("AA".."ZZ").to_a.rand return "#{post_towns.rand}#{number_1} #{number_2}#{letters}" end
ruby
def uk_post_code post_towns = %w(BM CB CV LE LI LS KT MK NE OX PL YO) # Can't remember any othes at the moment number_1 = rand(100).to_s number_2 = rand(100).to_s # Easier way to do this? letters = ("AA".."ZZ").to_a.rand return "#{post_towns.rand}#{number_1} #{number_2}#{letters}" end
[ "def", "uk_post_code", "post_towns", "=", "%w(", "BM", "CB", "CV", "LE", "LI", "LS", "KT", "MK", "NE", "OX", "PL", "YO", ")", "# Can't remember any othes at the moment", "number_1", "=", "rand", "(", "100", ")", ".", "to_s", "number_2", "=", "rand", "(", "100", ")", ".", "to_s", "# Easier way to do this? ", "letters", "=", "(", "\"AA\"", "..", "\"ZZ\"", ")", ".", "to_a", ".", "rand", "return", "\"#{post_towns.rand}#{number_1} #{number_2}#{letters}\"", "end" ]
Returns a string providing something in the general form of a UK post code. Like the zip codes, this might not actually be valid. Doesn't cover London whose codes are like "SE1".
[ "Returns", "a", "string", "providing", "something", "in", "the", "general", "form", "of", "a", "UK", "post", "code", ".", "Like", "the", "zip", "codes", "this", "might", "not", "actually", "be", "valid", ".", "Doesn", "t", "cover", "London", "whose", "codes", "are", "like", "SE1", "." ]
641271ea66e7837b2c4a9efa034d9ac75b4f487d
https://github.com/tomharris/random_data/blob/641271ea66e7837b2c4a9efa034d9ac75b4f487d/lib/random_data/locations.rb#L56-L65
2,517
thhermansen/google_static_maps_helper
lib/google_static_maps_helper/map.rb
GoogleStaticMapsHelper.Map.url
def url raise BuildDataMissing, "We have to have markers, paths or center and zoom set when url is called!" unless can_build? out = "#{API_URL}?" params = [] (REQUIRED_OPTIONS + OPTIONAL_OPTIONS).each do |key| value = send(key) params << "#{key}=#{URI.escape(value.to_s)}" unless value.nil? end out += params.join('&') params = [] grouped_markers.each_pair do |marker_options_as_url_params, markers| markers_locations = markers.map { |m| m.location_to_url }.join('|') params << "markers=#{marker_options_as_url_params}|#{markers_locations}" end out += "&#{params.join('&')}" unless params.empty? params = [] paths.each {|path| params << path.url_params} out += "&#{params.join('&')}" unless params.empty? out end
ruby
def url raise BuildDataMissing, "We have to have markers, paths or center and zoom set when url is called!" unless can_build? out = "#{API_URL}?" params = [] (REQUIRED_OPTIONS + OPTIONAL_OPTIONS).each do |key| value = send(key) params << "#{key}=#{URI.escape(value.to_s)}" unless value.nil? end out += params.join('&') params = [] grouped_markers.each_pair do |marker_options_as_url_params, markers| markers_locations = markers.map { |m| m.location_to_url }.join('|') params << "markers=#{marker_options_as_url_params}|#{markers_locations}" end out += "&#{params.join('&')}" unless params.empty? params = [] paths.each {|path| params << path.url_params} out += "&#{params.join('&')}" unless params.empty? out end
[ "def", "url", "raise", "BuildDataMissing", ",", "\"We have to have markers, paths or center and zoom set when url is called!\"", "unless", "can_build?", "out", "=", "\"#{API_URL}?\"", "params", "=", "[", "]", "(", "REQUIRED_OPTIONS", "+", "OPTIONAL_OPTIONS", ")", ".", "each", "do", "|", "key", "|", "value", "=", "send", "(", "key", ")", "params", "<<", "\"#{key}=#{URI.escape(value.to_s)}\"", "unless", "value", ".", "nil?", "end", "out", "+=", "params", ".", "join", "(", "'&'", ")", "params", "=", "[", "]", "grouped_markers", ".", "each_pair", "do", "|", "marker_options_as_url_params", ",", "markers", "|", "markers_locations", "=", "markers", ".", "map", "{", "|", "m", "|", "m", ".", "location_to_url", "}", ".", "join", "(", "'|'", ")", "params", "<<", "\"markers=#{marker_options_as_url_params}|#{markers_locations}\"", "end", "out", "+=", "\"&#{params.join('&')}\"", "unless", "params", ".", "empty?", "params", "=", "[", "]", "paths", ".", "each", "{", "|", "path", "|", "params", "<<", "path", ".", "url_params", "}", "out", "+=", "\"&#{params.join('&')}\"", "unless", "params", ".", "empty?", "out", "end" ]
Creates a new Map object <tt>:options</tt>:: The options available are the same as described in Google's API documentation[http://code.google.com/apis/maps/documentation/staticmaps/#Usage]. In short, valid options are: <tt>:size</tt>:: The size of the map. Can be a "wxh", [w,h] or {:width => x, :height => y} <tt>:sensor</tt>:: Set to true if your application is using a sensor. See the API doc. <tt>:center</tt>:: The center point of your map. Optional if you add markers or path to the map <tt>:zoom</tt>:: The zoom level you want, also optional as center <tt>:format</tt>:: Defaults to png <tt>:maptype</tt>:: Defaults to roadmap <tt>:mobile</tt>:: Returns map tiles better suited for mobile devices with small screens. <tt>:language</tt>:: The language used in the map Builds up a URL representing the state of this Map object
[ "Creates", "a", "new", "Map", "object" ]
31d2af983e17be736566bfac686b56c57385d64d
https://github.com/thhermansen/google_static_maps_helper/blob/31d2af983e17be736566bfac686b56c57385d64d/lib/google_static_maps_helper/map.rb#L50-L74
2,518
thhermansen/google_static_maps_helper
lib/google_static_maps_helper/map.rb
GoogleStaticMapsHelper.Map.grouped_markers
def grouped_markers markers.inject(Hash.new {|hash, key| hash[key] = []}) do |groups, marker| groups[marker.options_to_url_params] << marker groups end end
ruby
def grouped_markers markers.inject(Hash.new {|hash, key| hash[key] = []}) do |groups, marker| groups[marker.options_to_url_params] << marker groups end end
[ "def", "grouped_markers", "markers", ".", "inject", "(", "Hash", ".", "new", "{", "|", "hash", ",", "key", "|", "hash", "[", "key", "]", "=", "[", "]", "}", ")", "do", "|", "groups", ",", "marker", "|", "groups", "[", "marker", ".", "options_to_url_params", "]", "<<", "marker", "groups", "end", "end" ]
Returns the markers grouped by it's label, color and size. This is handy when building the URL because the API wants us to group together equal markers and just list the position of the markers thereafter in the URL.
[ "Returns", "the", "markers", "grouped", "by", "it", "s", "label", "color", "and", "size", "." ]
31d2af983e17be736566bfac686b56c57385d64d
https://github.com/thhermansen/google_static_maps_helper/blob/31d2af983e17be736566bfac686b56c57385d64d/lib/google_static_maps_helper/map.rb#L89-L94
2,519
thhermansen/google_static_maps_helper
lib/google_static_maps_helper/map.rb
GoogleStaticMapsHelper.Map.size=
def size=(size) unless size.nil? case size when String width, height = size.split('x') when Array width, height = size when Hash width = size[:width] height = size[:height] else raise "Don't know how to set size from #{size.class}!" end self.width = width if width self.height = height if height end end
ruby
def size=(size) unless size.nil? case size when String width, height = size.split('x') when Array width, height = size when Hash width = size[:width] height = size[:height] else raise "Don't know how to set size from #{size.class}!" end self.width = width if width self.height = height if height end end
[ "def", "size", "=", "(", "size", ")", "unless", "size", ".", "nil?", "case", "size", "when", "String", "width", ",", "height", "=", "size", ".", "split", "(", "'x'", ")", "when", "Array", "width", ",", "height", "=", "size", "when", "Hash", "width", "=", "size", "[", ":width", "]", "height", "=", "size", "[", ":height", "]", "else", "raise", "\"Don't know how to set size from #{size.class}!\"", "end", "self", ".", "width", "=", "width", "if", "width", "self", ".", "height", "=", "height", "if", "height", "end", "end" ]
Sets the size of the map <tt>size</tt>:: Can be a "wxh", [w,h] or {:width => x, :height => y}
[ "Sets", "the", "size", "of", "the", "map" ]
31d2af983e17be736566bfac686b56c57385d64d
https://github.com/thhermansen/google_static_maps_helper/blob/31d2af983e17be736566bfac686b56c57385d64d/lib/google_static_maps_helper/map.rb#L144-L161
2,520
tomharris/random_data
lib/random_data/text.rb
RandomData.Text.alphanumeric
def alphanumeric(size=16) s = "" size.times { s << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr } s end
ruby
def alphanumeric(size=16) s = "" size.times { s << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr } s end
[ "def", "alphanumeric", "(", "size", "=", "16", ")", "s", "=", "\"\"", "size", ".", "times", "{", "s", "<<", "(", "i", "=", "Kernel", ".", "rand", "(", "62", ")", ";", "i", "+=", "(", "(", "i", "<", "10", ")", "?", "48", ":", "(", "(", "i", "<", "36", ")", "?", "55", ":", "61", ")", ")", ")", ".", "chr", "}", "s", "end" ]
Methods to create random strings and paragraphs. Returns a string of random upper- and lowercase alphanumeric characters. Accepts a size parameters, defaults to 16 characters. >> Random.alphanumeric "Ke2jdknPYAI8uCXj" >> Random.alphanumeric(5) "7sj7i"
[ "Methods", "to", "create", "random", "strings", "and", "paragraphs", ".", "Returns", "a", "string", "of", "random", "upper", "-", "and", "lowercase", "alphanumeric", "characters", ".", "Accepts", "a", "size", "parameters", "defaults", "to", "16", "characters", "." ]
641271ea66e7837b2c4a9efa034d9ac75b4f487d
https://github.com/tomharris/random_data/blob/641271ea66e7837b2c4a9efa034d9ac75b4f487d/lib/random_data/text.rb#L17-L21
2,521
tomharris/random_data
lib/random_data/markov.rb
RandomData.MarkovGenerator.insert
def insert(result) # puts "insert called with #{result}" tabindex = Marshal.dump(@state) if @table[tabindex].has_key?(result) @table[tabindex][result] += 1 else @table[tabindex][result] = 1 end # puts "table #{@table.inspect}" next_state(result) end
ruby
def insert(result) # puts "insert called with #{result}" tabindex = Marshal.dump(@state) if @table[tabindex].has_key?(result) @table[tabindex][result] += 1 else @table[tabindex][result] = 1 end # puts "table #{@table.inspect}" next_state(result) end
[ "def", "insert", "(", "result", ")", "# puts \"insert called with #{result}\"", "tabindex", "=", "Marshal", ".", "dump", "(", "@state", ")", "if", "@table", "[", "tabindex", "]", ".", "has_key?", "(", "result", ")", "@table", "[", "tabindex", "]", "[", "result", "]", "+=", "1", "else", "@table", "[", "tabindex", "]", "[", "result", "]", "=", "1", "end", "# puts \"table #{@table.inspect}\"", "next_state", "(", "result", ")", "end" ]
given the next token of input add it to the table
[ "given", "the", "next", "token", "of", "input", "add", "it", "to", "the", "table" ]
641271ea66e7837b2c4a9efa034d9ac75b4f487d
https://github.com/tomharris/random_data/blob/641271ea66e7837b2c4a9efa034d9ac75b4f487d/lib/random_data/markov.rb#L16-L26
2,522
dennisreimann/masq
app/helpers/masq/personas_helper.rb
Masq.PersonasHelper.countries_for_select
def countries_for_select ::I18nData.countries.map{|pair| pair.reverse}.sort{|x,y| x.first <=> y.first} end
ruby
def countries_for_select ::I18nData.countries.map{|pair| pair.reverse}.sort{|x,y| x.first <=> y.first} end
[ "def", "countries_for_select", "::", "I18nData", ".", "countries", ".", "map", "{", "|", "pair", "|", "pair", ".", "reverse", "}", ".", "sort", "{", "|", "x", ",", "y", "|", "x", ".", "first", "<=>", "y", ".", "first", "}", "end" ]
get list of codes and names sorted by country name
[ "get", "list", "of", "codes", "and", "names", "sorted", "by", "country", "name" ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/helpers/masq/personas_helper.rb#L6-L8
2,523
dennisreimann/masq
app/helpers/masq/personas_helper.rb
Masq.PersonasHelper.languages_for_select
def languages_for_select ::I18nData.languages.map{|pair| pair.reverse}.sort{|x,y| x.first <=> y.first} end
ruby
def languages_for_select ::I18nData.languages.map{|pair| pair.reverse}.sort{|x,y| x.first <=> y.first} end
[ "def", "languages_for_select", "::", "I18nData", ".", "languages", ".", "map", "{", "|", "pair", "|", "pair", ".", "reverse", "}", ".", "sort", "{", "|", "x", ",", "y", "|", "x", ".", "first", "<=>", "y", ".", "first", "}", "end" ]
get list of codes and names sorted by language name
[ "get", "list", "of", "codes", "and", "names", "sorted", "by", "language", "name" ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/helpers/masq/personas_helper.rb#L11-L13
2,524
qoobaa/vcard
lib/vcard/vcard.rb
Vcard.Vcard.lines
def lines(name=nil) #:yield: Line # FIXME - this would be much easier if #lines was #each, and there was a # different #lines that returned an Enumerator that used #each unless block_given? map do |f| if( !name || f.name?(name) ) f2l(f) else nil end end.compact else each do |f| if( !name || f.name?(name) ) line = f2l(f) if line yield line end end end self end end
ruby
def lines(name=nil) #:yield: Line # FIXME - this would be much easier if #lines was #each, and there was a # different #lines that returned an Enumerator that used #each unless block_given? map do |f| if( !name || f.name?(name) ) f2l(f) else nil end end.compact else each do |f| if( !name || f.name?(name) ) line = f2l(f) if line yield line end end end self end end
[ "def", "lines", "(", "name", "=", "nil", ")", "#:yield: Line", "# FIXME - this would be much easier if #lines was #each, and there was a", "# different #lines that returned an Enumerator that used #each", "unless", "block_given?", "map", "do", "|", "f", "|", "if", "(", "!", "name", "||", "f", ".", "name?", "(", "name", ")", ")", "f2l", "(", "f", ")", "else", "nil", "end", "end", ".", "compact", "else", "each", "do", "|", "f", "|", "if", "(", "!", "name", "||", "f", ".", "name?", "(", "name", ")", ")", "line", "=", "f2l", "(", "f", ")", "if", "line", "yield", "line", "end", "end", "end", "self", "end", "end" ]
With no block, returns an Array of Line. If +name+ is specified, the Array will only contain the +Line+s with that +name+. The Array may be empty. If a block is given, each Line will be yielded instead of being returned in an Array.
[ "With", "no", "block", "returns", "an", "Array", "of", "Line", ".", "If", "+", "name", "+", "is", "specified", "the", "Array", "will", "only", "contain", "the", "+", "Line", "+", "s", "with", "that", "+", "name", "+", ".", "The", "Array", "may", "be", "empty", "." ]
0cab080676df262555e3adadc9a82fedc128d337
https://github.com/qoobaa/vcard/blob/0cab080676df262555e3adadc9a82fedc128d337/lib/vcard/vcard.rb#L578-L600
2,525
qoobaa/vcard
lib/vcard/vcard.rb
Vcard.Vcard.delete_if
def delete_if #:nodoc: :yield: line # Do in two steps to not mess up progress through the enumerator. rm = [] each do |f| line = f2l(f) if line && yield(line) rm << f # Hack - because we treat N and FN as one field if f.name? "N" rm << field("FN") end end end rm.each do |f| @fields.delete( f ) @cache.delete( f ) end end
ruby
def delete_if #:nodoc: :yield: line # Do in two steps to not mess up progress through the enumerator. rm = [] each do |f| line = f2l(f) if line && yield(line) rm << f # Hack - because we treat N and FN as one field if f.name? "N" rm << field("FN") end end end rm.each do |f| @fields.delete( f ) @cache.delete( f ) end end
[ "def", "delete_if", "#:nodoc: :yield: line", "# Do in two steps to not mess up progress through the enumerator.", "rm", "=", "[", "]", "each", "do", "|", "f", "|", "line", "=", "f2l", "(", "f", ")", "if", "line", "&&", "yield", "(", "line", ")", "rm", "<<", "f", "# Hack - because we treat N and FN as one field", "if", "f", ".", "name?", "\"N\"", "rm", "<<", "field", "(", "\"FN\"", ")", "end", "end", "end", "rm", ".", "each", "do", "|", "f", "|", "@fields", ".", "delete", "(", "f", ")", "@cache", ".", "delete", "(", "f", ")", "end", "end" ]
Delete +line+ if block yields true.
[ "Delete", "+", "line", "+", "if", "block", "yields", "true", "." ]
0cab080676df262555e3adadc9a82fedc128d337
https://github.com/qoobaa/vcard/blob/0cab080676df262555e3adadc9a82fedc128d337/lib/vcard/vcard.rb#L966-L987
2,526
ma2gedev/breadcrumble
lib/breadcrumble/action_controller.rb
Breadcrumble.ActionController.add_breadcrumb_to
def add_breadcrumb_to(name, url, trail_index) breadcrumb_trails @breadcrumb_trails[trail_index] ||= [] @breadcrumb_trails[trail_index] << { name: case name when Proc then name.call(self) else name end, url: case url when Proc then url.call(self) else url ? url_for(url) : nil end } end
ruby
def add_breadcrumb_to(name, url, trail_index) breadcrumb_trails @breadcrumb_trails[trail_index] ||= [] @breadcrumb_trails[trail_index] << { name: case name when Proc then name.call(self) else name end, url: case url when Proc then url.call(self) else url ? url_for(url) : nil end } end
[ "def", "add_breadcrumb_to", "(", "name", ",", "url", ",", "trail_index", ")", "breadcrumb_trails", "@breadcrumb_trails", "[", "trail_index", "]", "||=", "[", "]", "@breadcrumb_trails", "[", "trail_index", "]", "<<", "{", "name", ":", "case", "name", "when", "Proc", "then", "name", ".", "call", "(", "self", ")", "else", "name", "end", ",", "url", ":", "case", "url", "when", "Proc", "then", "url", ".", "call", "(", "self", ")", "else", "url", "?", "url_for", "(", "url", ")", ":", "nil", "end", "}", "end" ]
Add a breadcrumb to breadcrumb trail. @param trail_index index of breadcrumb trail @example add_breadcrumb_to("level 1", "level 1 url", 0)
[ "Add", "a", "breadcrumb", "to", "breadcrumb", "trail", "." ]
6a274b9b881d74aa69a8c3cf248fa73bacfd1d46
https://github.com/ma2gedev/breadcrumble/blob/6a274b9b881d74aa69a8c3cf248fa73bacfd1d46/lib/breadcrumble/action_controller.rb#L57-L70
2,527
dennisreimann/masq
lib/masq/authenticated_system.rb
Masq.AuthenticatedSystem.current_account=
def current_account=(new_account) if self.auth_type_used != :basic session[:account_id] = (new_account.nil? || new_account.is_a?(Symbol)) ? nil : new_account.id end @current_account = new_account || :false end
ruby
def current_account=(new_account) if self.auth_type_used != :basic session[:account_id] = (new_account.nil? || new_account.is_a?(Symbol)) ? nil : new_account.id end @current_account = new_account || :false end
[ "def", "current_account", "=", "(", "new_account", ")", "if", "self", ".", "auth_type_used", "!=", ":basic", "session", "[", ":account_id", "]", "=", "(", "new_account", ".", "nil?", "||", "new_account", ".", "is_a?", "(", "Symbol", ")", ")", "?", "nil", ":", "new_account", ".", "id", "end", "@current_account", "=", "new_account", "||", ":false", "end" ]
Store the given account id in the session.
[ "Store", "the", "given", "account", "id", "in", "the", "session", "." ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/lib/masq/authenticated_system.rb#L17-L22
2,528
dennisreimann/masq
lib/masq/authenticated_system.rb
Masq.AuthenticatedSystem.access_denied
def access_denied respond_to do |format| format.html do store_location redirect_to login_path end format.any do request_http_basic_authentication 'Web Password' end end end
ruby
def access_denied respond_to do |format| format.html do store_location redirect_to login_path end format.any do request_http_basic_authentication 'Web Password' end end end
[ "def", "access_denied", "respond_to", "do", "|", "format", "|", "format", ".", "html", "do", "store_location", "redirect_to", "login_path", "end", "format", ".", "any", "do", "request_http_basic_authentication", "'Web Password'", "end", "end", "end" ]
Redirect as appropriate when an access request fails. The default action is to redirect to the login screen. Override this method in your controllers if you want to have special behavior in case the account is not authorized to access the requested action. For example, a popup window might simply close itself.
[ "Redirect", "as", "appropriate", "when", "an", "access", "request", "fails", "." ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/lib/masq/authenticated_system.rb#L66-L76
2,529
jhass/open_graph_reader
lib/open_graph_reader/object.rb
OpenGraphReader.Object.[]=
def []= name, value if property?(name) public_send "#{name}=", value elsif OpenGraphReader.config.strict raise UndefinedPropertyError, "Undefined property #{name} on #{inspect}" end end
ruby
def []= name, value if property?(name) public_send "#{name}=", value elsif OpenGraphReader.config.strict raise UndefinedPropertyError, "Undefined property #{name} on #{inspect}" end end
[ "def", "[]=", "name", ",", "value", "if", "property?", "(", "name", ")", "public_send", "\"#{name}=\"", ",", "value", "elsif", "OpenGraphReader", ".", "config", ".", "strict", "raise", "UndefinedPropertyError", ",", "\"Undefined property #{name} on #{inspect}\"", "end", "end" ]
Set the property to the given value. @api private @param [#to_s] name @param [String, Object] value @raise [UndefinedPropertyError] If the requested property is undefined.
[ "Set", "the", "property", "to", "the", "given", "value", "." ]
5488354b7dd75b5411a881d734aa7176546e7cb4
https://github.com/jhass/open_graph_reader/blob/5488354b7dd75b5411a881d734aa7176546e7cb4/lib/open_graph_reader/object.rb#L81-L87
2,530
tomharris/random_data
lib/random_data/dates.rb
RandomData.Dates.date
def date(dayrange=10) if dayrange.is_a?(Range) offset = rand(dayrange.max-dayrange.min) + dayrange.min else offset = rand(dayrange*2) - dayrange end Date.today + offset end
ruby
def date(dayrange=10) if dayrange.is_a?(Range) offset = rand(dayrange.max-dayrange.min) + dayrange.min else offset = rand(dayrange*2) - dayrange end Date.today + offset end
[ "def", "date", "(", "dayrange", "=", "10", ")", "if", "dayrange", ".", "is_a?", "(", "Range", ")", "offset", "=", "rand", "(", "dayrange", ".", "max", "-", "dayrange", ".", "min", ")", "+", "dayrange", ".", "min", "else", "offset", "=", "rand", "(", "dayrange", "2", ")", "-", "dayrange", "end", "Date", ".", "today", "+", "offset", "end" ]
Returns a date within a specified range of days. If dayrange is an Integer, then the date returned will be plus or minus half what you specify. The default is ten days, so by default you will get a date within plus or minus five days of today. If dayrange is a Range, then you will get a date the falls between that range Example: Random.date # => a Date +/- 5 days of today Random.date(20) # => a Date +/- 10 days of today Random.date(-60..-30) # => a Date between 60 days ago and 30 days ago
[ "Returns", "a", "date", "within", "a", "specified", "range", "of", "days", ".", "If", "dayrange", "is", "an", "Integer", "then", "the", "date", "returned", "will", "be", "plus", "or", "minus", "half", "what", "you", "specify", ".", "The", "default", "is", "ten", "days", "so", "by", "default", "you", "will", "get", "a", "date", "within", "plus", "or", "minus", "five", "days", "of", "today", "." ]
641271ea66e7837b2c4a9efa034d9ac75b4f487d
https://github.com/tomharris/random_data/blob/641271ea66e7837b2c4a9efa034d9ac75b4f487d/lib/random_data/dates.rb#L21-L28
2,531
tomharris/random_data
lib/random_data/dates.rb
RandomData.Dates.date_between
def date_between(range) min_date = range.min.is_a?(Date) ? range.min : Date.parse(range.min) max_date = range.max.is_a?(Date) ? range.max : Date.parse(range.max) diff = (max_date - min_date).to_i min_date + rand(diff) end
ruby
def date_between(range) min_date = range.min.is_a?(Date) ? range.min : Date.parse(range.min) max_date = range.max.is_a?(Date) ? range.max : Date.parse(range.max) diff = (max_date - min_date).to_i min_date + rand(diff) end
[ "def", "date_between", "(", "range", ")", "min_date", "=", "range", ".", "min", ".", "is_a?", "(", "Date", ")", "?", "range", ".", "min", ":", "Date", ".", "parse", "(", "range", ".", "min", ")", "max_date", "=", "range", ".", "max", ".", "is_a?", "(", "Date", ")", "?", "range", ".", "max", ":", "Date", ".", "parse", "(", "range", ".", "max", ")", "diff", "=", "(", "max_date", "-", "min_date", ")", ".", "to_i", "min_date", "+", "rand", "(", "diff", ")", "end" ]
Returns a date within the specified Range. The Range can be Date or String objects. Example: min = Date.parse('1966-11-15') max = Date.parse('1990-01-01') Random.date(min..max) # => a Date between 11/15/1996 and 1/1/1990 Random.date('1966-11-15'..'1990-01-01') # => a Date between 11/15/1996 and 1/1/1990
[ "Returns", "a", "date", "within", "the", "specified", "Range", ".", "The", "Range", "can", "be", "Date", "or", "String", "objects", "." ]
641271ea66e7837b2c4a9efa034d9ac75b4f487d
https://github.com/tomharris/random_data/blob/641271ea66e7837b2c4a9efa034d9ac75b4f487d/lib/random_data/dates.rb#L38-L44
2,532
thhermansen/google_static_maps_helper
lib/google_static_maps_helper/path.rb
GoogleStaticMapsHelper.Path.url_params
def url_params # :nodoc: raise BuildDataMissing, "Need at least 2 points to create a path!" unless can_build? out = 'path=' path_params = OPTIONAL_OPTIONS.inject([]) do |path_params, attribute| value = send(attribute) path_params << "#{attribute}:#{URI.escape(value.to_s)}" unless value.nil? path_params end.join('|') out += "#{path_params}|" unless path_params.empty? out += encoded_url_points if encoding_points? out += unencoded_url_points unless encoding_points? out end
ruby
def url_params # :nodoc: raise BuildDataMissing, "Need at least 2 points to create a path!" unless can_build? out = 'path=' path_params = OPTIONAL_OPTIONS.inject([]) do |path_params, attribute| value = send(attribute) path_params << "#{attribute}:#{URI.escape(value.to_s)}" unless value.nil? path_params end.join('|') out += "#{path_params}|" unless path_params.empty? out += encoded_url_points if encoding_points? out += unencoded_url_points unless encoding_points? out end
[ "def", "url_params", "# :nodoc:", "raise", "BuildDataMissing", ",", "\"Need at least 2 points to create a path!\"", "unless", "can_build?", "out", "=", "'path='", "path_params", "=", "OPTIONAL_OPTIONS", ".", "inject", "(", "[", "]", ")", "do", "|", "path_params", ",", "attribute", "|", "value", "=", "send", "(", "attribute", ")", "path_params", "<<", "\"#{attribute}:#{URI.escape(value.to_s)}\"", "unless", "value", ".", "nil?", "path_params", "end", ".", "join", "(", "'|'", ")", "out", "+=", "\"#{path_params}|\"", "unless", "path_params", ".", "empty?", "out", "+=", "encoded_url_points", "if", "encoding_points?", "out", "+=", "unencoded_url_points", "unless", "encoding_points?", "out", "end" ]
Creates a new Path which you can push points on to to make up lines or polygons The following options are available, for more information see the Google API documentation[http://code.google.com/apis/maps/documentation/staticmaps/#Paths]. <tt>:weight</tt>:: The weight is the thickness of the line, defaults to 5 <tt>:color</tt>:: The color of the border can either be a textual representation like red, green, blue, black etc or as a 24-bit (0xAABBCC) or 32-bit hex value (0xAABBCCDD). When 32-bit values are given the two last bits will represent the alpha transparency value. <tt>:fillcolor</tt>:: With the fill color set you'll get a polygon in the map. The color value can be the same as described in the <tt>:color</tt>. When used, the static map will automatically create a closed shape. <tt>:points</tt>:: An array of points. You can mix objects responding to lng and lat, and a Hash with lng and lat keys. <tt>:encode_points:: A flag which tells us if we should encode the points in this path or not. Defaults to <tt>true</tt> Returns a string representation of this Path Used by the Map when building the URL
[ "Creates", "a", "new", "Path", "which", "you", "can", "push", "points", "on", "to", "to", "make", "up", "lines", "or", "polygons" ]
31d2af983e17be736566bfac686b56c57385d64d
https://github.com/thhermansen/google_static_maps_helper/blob/31d2af983e17be736566bfac686b56c57385d64d/lib/google_static_maps_helper/path.rb#L42-L57
2,533
thhermansen/google_static_maps_helper
lib/google_static_maps_helper/path.rb
GoogleStaticMapsHelper.Path.points=
def points=(array) raise ArgumentError unless array.is_a? Array @points = [] array.each {|point| self << point} end
ruby
def points=(array) raise ArgumentError unless array.is_a? Array @points = [] array.each {|point| self << point} end
[ "def", "points", "=", "(", "array", ")", "raise", "ArgumentError", "unless", "array", ".", "is_a?", "Array", "@points", "=", "[", "]", "array", ".", "each", "{", "|", "point", "|", "self", "<<", "point", "}", "end" ]
Sets the points of this Path. *WARNING* Using this method will clear out any points which might be set.
[ "Sets", "the", "points", "of", "this", "Path", "." ]
31d2af983e17be736566bfac686b56c57385d64d
https://github.com/thhermansen/google_static_maps_helper/blob/31d2af983e17be736566bfac686b56c57385d64d/lib/google_static_maps_helper/path.rb#L65-L69
2,534
dennisreimann/masq
lib/masq/openid_server_system.rb
Masq.OpenidServerSystem.add_pape
def add_pape(resp, policies = [], nist_auth_level = 0, auth_time = nil) if papereq = OpenID::PAPE::Request.from_openid_request(openid_request) paperesp = OpenID::PAPE::Response.new policies.each { |p| paperesp.add_policy_uri(p) } paperesp.nist_auth_level = nist_auth_level paperesp.auth_time = auth_time.utc.iso8601 resp.add_extension(paperesp) end resp end
ruby
def add_pape(resp, policies = [], nist_auth_level = 0, auth_time = nil) if papereq = OpenID::PAPE::Request.from_openid_request(openid_request) paperesp = OpenID::PAPE::Response.new policies.each { |p| paperesp.add_policy_uri(p) } paperesp.nist_auth_level = nist_auth_level paperesp.auth_time = auth_time.utc.iso8601 resp.add_extension(paperesp) end resp end
[ "def", "add_pape", "(", "resp", ",", "policies", "=", "[", "]", ",", "nist_auth_level", "=", "0", ",", "auth_time", "=", "nil", ")", "if", "papereq", "=", "OpenID", "::", "PAPE", "::", "Request", ".", "from_openid_request", "(", "openid_request", ")", "paperesp", "=", "OpenID", "::", "PAPE", "::", "Response", ".", "new", "policies", ".", "each", "{", "|", "p", "|", "paperesp", ".", "add_policy_uri", "(", "p", ")", "}", "paperesp", ".", "nist_auth_level", "=", "nist_auth_level", "paperesp", ".", "auth_time", "=", "auth_time", ".", "utc", ".", "iso8601", "resp", ".", "add_extension", "(", "paperesp", ")", "end", "resp", "end" ]
Adds PAPE information for your server to an OpenID response.
[ "Adds", "PAPE", "information", "for", "your", "server", "to", "an", "OpenID", "response", "." ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/lib/masq/openid_server_system.rb#L74-L83
2,535
dennisreimann/masq
lib/masq/openid_server_system.rb
Masq.OpenidServerSystem.render_openid_response
def render_openid_response(resp) signed_response = openid_server.signatory.sign(resp) if resp.needs_signing web_response = openid_server.encode_response(resp) case web_response.code when OpenID::Server::HTTP_OK then render(:text => web_response.body, :status => 200) when OpenID::Server::HTTP_REDIRECT then redirect_to(web_response.headers['location']) else render(:text => web_response.body, :status => 400) end end
ruby
def render_openid_response(resp) signed_response = openid_server.signatory.sign(resp) if resp.needs_signing web_response = openid_server.encode_response(resp) case web_response.code when OpenID::Server::HTTP_OK then render(:text => web_response.body, :status => 200) when OpenID::Server::HTTP_REDIRECT then redirect_to(web_response.headers['location']) else render(:text => web_response.body, :status => 400) end end
[ "def", "render_openid_response", "(", "resp", ")", "signed_response", "=", "openid_server", ".", "signatory", ".", "sign", "(", "resp", ")", "if", "resp", ".", "needs_signing", "web_response", "=", "openid_server", ".", "encode_response", "(", "resp", ")", "case", "web_response", ".", "code", "when", "OpenID", "::", "Server", "::", "HTTP_OK", "then", "render", "(", ":text", "=>", "web_response", ".", "body", ",", ":status", "=>", "200", ")", "when", "OpenID", "::", "Server", "::", "HTTP_REDIRECT", "then", "redirect_to", "(", "web_response", ".", "headers", "[", "'location'", "]", ")", "else", "render", "(", ":text", "=>", "web_response", ".", "body", ",", ":status", "=>", "400", ")", "end", "end" ]
Renders the final response output
[ "Renders", "the", "final", "response", "output" ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/lib/masq/openid_server_system.rb#L92-L100
2,536
dennisreimann/masq
app/models/masq/persona.rb
Masq.Persona.property
def property(type) prop = Persona.mappings.detect { |i| i[1].include?(type) } prop ? self.send(prop[0]).to_s : nil end
ruby
def property(type) prop = Persona.mappings.detect { |i| i[1].include?(type) } prop ? self.send(prop[0]).to_s : nil end
[ "def", "property", "(", "type", ")", "prop", "=", "Persona", ".", "mappings", ".", "detect", "{", "|", "i", "|", "i", "[", "1", "]", ".", "include?", "(", "type", ")", "}", "prop", "?", "self", ".", "send", "(", "prop", "[", "0", "]", ")", ".", "to_s", ":", "nil", "end" ]
Returns the personas attribute for the given SReg name or AX Type URI
[ "Returns", "the", "personas", "attribute", "for", "the", "given", "SReg", "name", "or", "AX", "Type", "URI" ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/models/masq/persona.rb#L26-L29
2,537
ustasb/pandata
lib/pandata/cli.rb
Pandata.CLI.format_data
def format_data(data, json = false) if json JSON.generate(data) else data.map do |category, cat_data| # Capitalize each word in the category symbol. # e.g. :liked_tracks becomes 'Liked Tracks' title = category.to_s.split('_').map(&:capitalize).join(' ') output = if cat_data.empty? " ** No Data **\n" else case category when /liked_tracks/ formatter.tracks(cat_data) when /liked_artists|liked_stations/ formatter.sort_list(cat_data) when :liked_albums formatter.albums(cat_data) when /following|followers/ formatter.followx(cat_data) end end "#{title}:\n#{output}" end.join end end
ruby
def format_data(data, json = false) if json JSON.generate(data) else data.map do |category, cat_data| # Capitalize each word in the category symbol. # e.g. :liked_tracks becomes 'Liked Tracks' title = category.to_s.split('_').map(&:capitalize).join(' ') output = if cat_data.empty? " ** No Data **\n" else case category when /liked_tracks/ formatter.tracks(cat_data) when /liked_artists|liked_stations/ formatter.sort_list(cat_data) when :liked_albums formatter.albums(cat_data) when /following|followers/ formatter.followx(cat_data) end end "#{title}:\n#{output}" end.join end end
[ "def", "format_data", "(", "data", ",", "json", "=", "false", ")", "if", "json", "JSON", ".", "generate", "(", "data", ")", "else", "data", ".", "map", "do", "|", "category", ",", "cat_data", "|", "# Capitalize each word in the category symbol.", "# e.g. :liked_tracks becomes 'Liked Tracks'", "title", "=", "category", ".", "to_s", ".", "split", "(", "'_'", ")", ".", "map", "(", ":capitalize", ")", ".", "join", "(", "' '", ")", "output", "=", "if", "cat_data", ".", "empty?", "\" ** No Data **\\n\"", "else", "case", "category", "when", "/", "/", "formatter", ".", "tracks", "(", "cat_data", ")", "when", "/", "/", "formatter", ".", "sort_list", "(", "cat_data", ")", "when", ":liked_albums", "formatter", ".", "albums", "(", "cat_data", ")", "when", "/", "/", "formatter", ".", "followx", "(", "cat_data", ")", "end", "end", "\"#{title}:\\n#{output}\"", "end", ".", "join", "end", "end" ]
Formats data as a string list or JSON. @param data [Hash] @param json [Boolean] @return [String]
[ "Formats", "data", "as", "a", "string", "list", "or", "JSON", "." ]
c75f83813171bc6149eca53ff310dedca1a7a1cb
https://github.com/ustasb/pandata/blob/c75f83813171bc6149eca53ff310dedca1a7a1cb/lib/pandata/cli.rb#L75-L102
2,538
ustasb/pandata
lib/pandata/cli.rb
Pandata.CLI.download_data
def download_data scraper_data = {} @data_to_get.each do |data_category| if /liked_(.*)/ =~ data_category argument = $1.to_sym # :tracks, :artists, :stations or :albums scraper_data[data_category] = @scraper.public_send(:likes, argument) else scraper_data[data_category] = @scraper.public_send(data_category) end end scraper_data end
ruby
def download_data scraper_data = {} @data_to_get.each do |data_category| if /liked_(.*)/ =~ data_category argument = $1.to_sym # :tracks, :artists, :stations or :albums scraper_data[data_category] = @scraper.public_send(:likes, argument) else scraper_data[data_category] = @scraper.public_send(data_category) end end scraper_data end
[ "def", "download_data", "scraper_data", "=", "{", "}", "@data_to_get", ".", "each", "do", "|", "data_category", "|", "if", "/", "/", "=~", "data_category", "argument", "=", "$1", ".", "to_sym", "# :tracks, :artists, :stations or :albums", "scraper_data", "[", "data_category", "]", "=", "@scraper", ".", "public_send", "(", ":likes", ",", "argument", ")", "else", "scraper_data", "[", "data_category", "]", "=", "@scraper", ".", "public_send", "(", "data_category", ")", "end", "end", "scraper_data", "end" ]
Downloads the user's desired data. @return [Hash]
[ "Downloads", "the", "user", "s", "desired", "data", "." ]
c75f83813171bc6149eca53ff310dedca1a7a1cb
https://github.com/ustasb/pandata/blob/c75f83813171bc6149eca53ff310dedca1a7a1cb/lib/pandata/cli.rb#L106-L119
2,539
ustasb/pandata
lib/pandata/cli.rb
Pandata.CLI.scraper_for
def scraper_for(user_id) scraper = Pandata::Scraper.get(user_id) if scraper.kind_of?(Array) log "No exact match for '#{user_id}'." unless scraper.empty? log "\nWebname results for '#{user_id}':\n#{formatter.list(scraper)}" end raise PandataError, "Could not create a scraper for '#{user_id}'." end scraper end
ruby
def scraper_for(user_id) scraper = Pandata::Scraper.get(user_id) if scraper.kind_of?(Array) log "No exact match for '#{user_id}'." unless scraper.empty? log "\nWebname results for '#{user_id}':\n#{formatter.list(scraper)}" end raise PandataError, "Could not create a scraper for '#{user_id}'." end scraper end
[ "def", "scraper_for", "(", "user_id", ")", "scraper", "=", "Pandata", "::", "Scraper", ".", "get", "(", "user_id", ")", "if", "scraper", ".", "kind_of?", "(", "Array", ")", "log", "\"No exact match for '#{user_id}'.\"", "unless", "scraper", ".", "empty?", "log", "\"\\nWebname results for '#{user_id}':\\n#{formatter.list(scraper)}\"", "end", "raise", "PandataError", ",", "\"Could not create a scraper for '#{user_id}'.\"", "end", "scraper", "end" ]
Returns a scraper for the user's id. @param user_id [String] webname or email @return [Pandata::Scraper]
[ "Returns", "a", "scraper", "for", "the", "user", "s", "id", "." ]
c75f83813171bc6149eca53ff310dedca1a7a1cb
https://github.com/ustasb/pandata/blob/c75f83813171bc6149eca53ff310dedca1a7a1cb/lib/pandata/cli.rb#L124-L138
2,540
dennisreimann/masq
app/models/masq/site.rb
Masq.Site.ax_fetch=
def ax_fetch=(props) props.each_pair do |property, details| release_policies.build(:property => property, :type_identifier => details['type']) if details['value'] end end
ruby
def ax_fetch=(props) props.each_pair do |property, details| release_policies.build(:property => property, :type_identifier => details['type']) if details['value'] end end
[ "def", "ax_fetch", "=", "(", "props", ")", "props", ".", "each_pair", "do", "|", "property", ",", "details", "|", "release_policies", ".", "build", "(", ":property", "=>", "property", ",", ":type_identifier", "=>", "details", "[", "'type'", "]", ")", "if", "details", "[", "'value'", "]", "end", "end" ]
Generates a release policy for each property that has a value. This setter is used in the server controllers complete action to set the attributes recieved from the decision form.
[ "Generates", "a", "release", "policy", "for", "each", "property", "that", "has", "a", "value", ".", "This", "setter", "is", "used", "in", "the", "server", "controllers", "complete", "action", "to", "set", "the", "attributes", "recieved", "from", "the", "decision", "form", "." ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/models/masq/site.rb#L29-L33
2,541
dennisreimann/masq
app/models/masq/site.rb
Masq.Site.sreg_properties
def sreg_properties props = {} release_policies.each do |rp| is_sreg = (rp.property == rp.type_identifier) props[rp.property] = persona.property(rp.property) if is_sreg end props end
ruby
def sreg_properties props = {} release_policies.each do |rp| is_sreg = (rp.property == rp.type_identifier) props[rp.property] = persona.property(rp.property) if is_sreg end props end
[ "def", "sreg_properties", "props", "=", "{", "}", "release_policies", ".", "each", "do", "|", "rp", "|", "is_sreg", "=", "(", "rp", ".", "property", "==", "rp", ".", "type_identifier", ")", "props", "[", "rp", ".", "property", "]", "=", "persona", ".", "property", "(", "rp", ".", "property", ")", "if", "is_sreg", "end", "props", "end" ]
Returns a hash with all released SReg properties. SReg properties have a type_identifier matching their property name
[ "Returns", "a", "hash", "with", "all", "released", "SReg", "properties", ".", "SReg", "properties", "have", "a", "type_identifier", "matching", "their", "property", "name" ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/models/masq/site.rb#L46-L53
2,542
dennisreimann/masq
app/models/masq/site.rb
Masq.Site.ax_properties
def ax_properties props = {} release_policies.each do |rp| if rp.type_identifier.match("://") props["type.#{rp.property}"] = rp.type_identifier props["value.#{rp.property}"] = persona.property(rp.type_identifier ) end end props end
ruby
def ax_properties props = {} release_policies.each do |rp| if rp.type_identifier.match("://") props["type.#{rp.property}"] = rp.type_identifier props["value.#{rp.property}"] = persona.property(rp.type_identifier ) end end props end
[ "def", "ax_properties", "props", "=", "{", "}", "release_policies", ".", "each", "do", "|", "rp", "|", "if", "rp", ".", "type_identifier", ".", "match", "(", "\"://\"", ")", "props", "[", "\"type.#{rp.property}\"", "]", "=", "rp", ".", "type_identifier", "props", "[", "\"value.#{rp.property}\"", "]", "=", "persona", ".", "property", "(", "rp", ".", "type_identifier", ")", "end", "end", "props", "end" ]
Returns a hash with all released AX properties. AX properties have an URL as type_identifier.
[ "Returns", "a", "hash", "with", "all", "released", "AX", "properties", ".", "AX", "properties", "have", "an", "URL", "as", "type_identifier", "." ]
bc6b6d84fe06811b9de19e7863c53c6bfad201fe
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/models/masq/site.rb#L57-L66
2,543
ustasb/pandata
lib/pandata/data_formatter.rb
Pandata.DataFormatter.custom_sort
def custom_sort(enumerable) sorted_array = enumerable.sort_by do |key, _| key.sub(/^the\s*/i, '').downcase end # sort_by() returns an array when called on hashes. if enumerable.kind_of?(Hash) # Rebuild the hash. sorted_hash = {} sorted_array.each { |item| sorted_hash[item[0]] = item[1] } sorted_hash else sorted_array end end
ruby
def custom_sort(enumerable) sorted_array = enumerable.sort_by do |key, _| key.sub(/^the\s*/i, '').downcase end # sort_by() returns an array when called on hashes. if enumerable.kind_of?(Hash) # Rebuild the hash. sorted_hash = {} sorted_array.each { |item| sorted_hash[item[0]] = item[1] } sorted_hash else sorted_array end end
[ "def", "custom_sort", "(", "enumerable", ")", "sorted_array", "=", "enumerable", ".", "sort_by", "do", "|", "key", ",", "_", "|", "key", ".", "sub", "(", "/", "\\s", "/i", ",", "''", ")", ".", "downcase", "end", "# sort_by() returns an array when called on hashes.", "if", "enumerable", ".", "kind_of?", "(", "Hash", ")", "# Rebuild the hash.", "sorted_hash", "=", "{", "}", "sorted_array", ".", "each", "{", "|", "item", "|", "sorted_hash", "[", "item", "[", "0", "]", "]", "=", "item", "[", "1", "]", "}", "sorted_hash", "else", "sorted_array", "end", "end" ]
Sorts alphabetically ignoring the initial 'The' when sorting strings. Also case-insensitive to prevent lowercase names from being sorted last. @param enumerable [Array, Hash] @return [Array, Hash]
[ "Sorts", "alphabetically", "ignoring", "the", "initial", "The", "when", "sorting", "strings", ".", "Also", "case", "-", "insensitive", "to", "prevent", "lowercase", "names", "from", "being", "sorted", "last", "." ]
c75f83813171bc6149eca53ff310dedca1a7a1cb
https://github.com/ustasb/pandata/blob/c75f83813171bc6149eca53ff310dedca1a7a1cb/lib/pandata/data_formatter.rb#L53-L67
2,544
tomharris/random_data
lib/random_data/array_randomizer.rb
RandomData.ArrayRandomizer.roulette
def roulette(k=1) wheel = [] weight = 0 # Create the cumulative array. self.each do |x| raise "Illegal negative weight #{x}" if x < 0 wheel.push(weight += x) end # print "wheel is #{wheel.inspect}\n"; # print "weight is #{weight.inspect}\n"; raise "Array had all zero weights" if weight.zero? wheel.push(weight + 1) #Add extra element if block_given? k.times do r = Kernel.rand() # so we don't pick up that from array. # print "r is #{r.inspect}\n"; roll = weight.to_f * r # print "roll is #{roll.inspect}\n"; 0.upto(self.size - 1) do |i| if wheel[i+1] > roll yield i break end # if end # upto end # if block_given? return nil else r = Kernel.rand() # so we don't pick up that from array. # print "r is #{r.inspect}\n"; roll = weight.to_f * r # print "roll is #{roll.inspect}\n"; 0.upto(self.size - 1) do |i| return i if wheel[i+1] > roll end end end
ruby
def roulette(k=1) wheel = [] weight = 0 # Create the cumulative array. self.each do |x| raise "Illegal negative weight #{x}" if x < 0 wheel.push(weight += x) end # print "wheel is #{wheel.inspect}\n"; # print "weight is #{weight.inspect}\n"; raise "Array had all zero weights" if weight.zero? wheel.push(weight + 1) #Add extra element if block_given? k.times do r = Kernel.rand() # so we don't pick up that from array. # print "r is #{r.inspect}\n"; roll = weight.to_f * r # print "roll is #{roll.inspect}\n"; 0.upto(self.size - 1) do |i| if wheel[i+1] > roll yield i break end # if end # upto end # if block_given? return nil else r = Kernel.rand() # so we don't pick up that from array. # print "r is #{r.inspect}\n"; roll = weight.to_f * r # print "roll is #{roll.inspect}\n"; 0.upto(self.size - 1) do |i| return i if wheel[i+1] > roll end end end
[ "def", "roulette", "(", "k", "=", "1", ")", "wheel", "=", "[", "]", "weight", "=", "0", "# Create the cumulative array.", "self", ".", "each", "do", "|", "x", "|", "raise", "\"Illegal negative weight #{x}\"", "if", "x", "<", "0", "wheel", ".", "push", "(", "weight", "+=", "x", ")", "end", "# print \"wheel is #{wheel.inspect}\\n\";", "# print \"weight is #{weight.inspect}\\n\";", "raise", "\"Array had all zero weights\"", "if", "weight", ".", "zero?", "wheel", ".", "push", "(", "weight", "+", "1", ")", "#Add extra element", "if", "block_given?", "k", ".", "times", "do", "r", "=", "Kernel", ".", "rand", "(", ")", "# so we don't pick up that from array.", "# print \"r is #{r.inspect}\\n\";", "roll", "=", "weight", ".", "to_f", "*", "r", "# print \"roll is #{roll.inspect}\\n\";", "0", ".", "upto", "(", "self", ".", "size", "-", "1", ")", "do", "|", "i", "|", "if", "wheel", "[", "i", "+", "1", "]", ">", "roll", "yield", "i", "break", "end", "# if", "end", "# upto", "end", "# if block_given?", "return", "nil", "else", "r", "=", "Kernel", ".", "rand", "(", ")", "# so we don't pick up that from array.", "# print \"r is #{r.inspect}\\n\";", "roll", "=", "weight", ".", "to_f", "*", "r", "# print \"roll is #{roll.inspect}\\n\";", "0", ".", "upto", "(", "self", ".", "size", "-", "1", ")", "do", "|", "i", "|", "return", "i", "if", "wheel", "[", "i", "+", "1", "]", ">", "roll", "end", "end", "end" ]
Takes an array of non-negative weights and returns the index selected by a roulette wheel weighted according to those weights. If a block is given then k is used to determine how many times the block is called. In this case nil is returned.
[ "Takes", "an", "array", "of", "non", "-", "negative", "weights", "and", "returns", "the", "index", "selected", "by", "a", "roulette", "wheel", "weighted", "according", "to", "those", "weights", ".", "If", "a", "block", "is", "given", "then", "k", "is", "used", "to", "determine", "how", "many", "times", "the", "block", "is", "called", ".", "In", "this", "case", "nil", "is", "returned", "." ]
641271ea66e7837b2c4a9efa034d9ac75b4f487d
https://github.com/tomharris/random_data/blob/641271ea66e7837b2c4a9efa034d9ac75b4f487d/lib/random_data/array_randomizer.rb#L22-L57
2,545
jhass/open_graph_reader
lib/open_graph_reader/fetcher.rb
OpenGraphReader.Fetcher.body
def body fetch_body unless fetched? raise NoOpenGraphDataError, "No response body received for #{@uri}" if fetch_failed? raise NoOpenGraphDataError, "Did not receive a HTML site at #{@uri}" unless html? @get_response.body end
ruby
def body fetch_body unless fetched? raise NoOpenGraphDataError, "No response body received for #{@uri}" if fetch_failed? raise NoOpenGraphDataError, "Did not receive a HTML site at #{@uri}" unless html? @get_response.body end
[ "def", "body", "fetch_body", "unless", "fetched?", "raise", "NoOpenGraphDataError", ",", "\"No response body received for #{@uri}\"", "if", "fetch_failed?", "raise", "NoOpenGraphDataError", ",", "\"Did not receive a HTML site at #{@uri}\"", "unless", "html?", "@get_response", ".", "body", "end" ]
Retrieve the body @todo Custom error class @raise [ArgumentError] The received content does not seems to be HTML. @return [String]
[ "Retrieve", "the", "body" ]
5488354b7dd75b5411a881d734aa7176546e7cb4
https://github.com/jhass/open_graph_reader/blob/5488354b7dd75b5411a881d734aa7176546e7cb4/lib/open_graph_reader/fetcher.rb#L70-L75
2,546
jhass/open_graph_reader
lib/open_graph_reader/fetcher.rb
OpenGraphReader.Fetcher.html?
def html? fetch_headers unless fetched_headers? response = @get_response || @head_response return false if fetch_failed? return false unless response return false unless response.success? return false unless response["content-type"] response["content-type"].include? "text/html" end
ruby
def html? fetch_headers unless fetched_headers? response = @get_response || @head_response return false if fetch_failed? return false unless response return false unless response.success? return false unless response["content-type"] response["content-type"].include? "text/html" end
[ "def", "html?", "fetch_headers", "unless", "fetched_headers?", "response", "=", "@get_response", "||", "@head_response", "return", "false", "if", "fetch_failed?", "return", "false", "unless", "response", "return", "false", "unless", "response", ".", "success?", "return", "false", "unless", "response", "[", "\"content-type\"", "]", "response", "[", "\"content-type\"", "]", ".", "include?", "\"text/html\"", "end" ]
Whether the target URI seems to return HTML @return [Bool]
[ "Whether", "the", "target", "URI", "seems", "to", "return", "HTML" ]
5488354b7dd75b5411a881d734aa7176546e7cb4
https://github.com/jhass/open_graph_reader/blob/5488354b7dd75b5411a881d734aa7176546e7cb4/lib/open_graph_reader/fetcher.rb#L80-L88
2,547
cldwalker/boson
lib/boson/scientist.rb
Boson.Scientist.redefine_command
def redefine_command(obj, command) cmd_block = redefine_command_block(obj, command) @no_option_commands << command if command.options.nil? [command.name, command.alias].compact.each {|e| obj.singleton_class.send(:define_method, e, cmd_block) } rescue Error warn "Error: #{$!.message}" end
ruby
def redefine_command(obj, command) cmd_block = redefine_command_block(obj, command) @no_option_commands << command if command.options.nil? [command.name, command.alias].compact.each {|e| obj.singleton_class.send(:define_method, e, cmd_block) } rescue Error warn "Error: #{$!.message}" end
[ "def", "redefine_command", "(", "obj", ",", "command", ")", "cmd_block", "=", "redefine_command_block", "(", "obj", ",", "command", ")", "@no_option_commands", "<<", "command", "if", "command", ".", "options", ".", "nil?", "[", "command", ".", "name", ",", "command", ".", "alias", "]", ".", "compact", ".", "each", "{", "|", "e", "|", "obj", ".", "singleton_class", ".", "send", "(", ":define_method", ",", "e", ",", "cmd_block", ")", "}", "rescue", "Error", "warn", "\"Error: #{$!.message}\"", "end" ]
Redefines an object's method with a Command of the same name.
[ "Redefines", "an", "object", "s", "method", "with", "a", "Command", "of", "the", "same", "name", "." ]
17fe830fefd3dc41d90af01d191f074306591f32
https://github.com/cldwalker/boson/blob/17fe830fefd3dc41d90af01d191f074306591f32/lib/boson/scientist.rb#L44-L52
2,548
cldwalker/boson
lib/boson/scientist.rb
Boson.Scientist.redefine_command_block
def redefine_command_block(obj, command) object_methods(obj)[command.name] ||= begin obj.method(command.name) rescue NameError raise Error, "No method exists to redefine command '#{command.name}'." end lambda {|*args| Scientist.analyze(obj, command, args) {|args| Scientist.object_methods(obj)[command.name].call(*args) } } end
ruby
def redefine_command_block(obj, command) object_methods(obj)[command.name] ||= begin obj.method(command.name) rescue NameError raise Error, "No method exists to redefine command '#{command.name}'." end lambda {|*args| Scientist.analyze(obj, command, args) {|args| Scientist.object_methods(obj)[command.name].call(*args) } } end
[ "def", "redefine_command_block", "(", "obj", ",", "command", ")", "object_methods", "(", "obj", ")", "[", "command", ".", "name", "]", "||=", "begin", "obj", ".", "method", "(", "command", ".", "name", ")", "rescue", "NameError", "raise", "Error", ",", "\"No method exists to redefine command '#{command.name}'.\"", "end", "lambda", "{", "|", "*", "args", "|", "Scientist", ".", "analyze", "(", "obj", ",", "command", ",", "args", ")", "{", "|", "args", "|", "Scientist", ".", "object_methods", "(", "obj", ")", "[", "command", ".", "name", "]", ".", "call", "(", "args", ")", "}", "}", "end" ]
The actual method which redefines a command's original method
[ "The", "actual", "method", "which", "redefines", "a", "command", "s", "original", "method" ]
17fe830fefd3dc41d90af01d191f074306591f32
https://github.com/cldwalker/boson/blob/17fe830fefd3dc41d90af01d191f074306591f32/lib/boson/scientist.rb#L79-L90
2,549
cldwalker/boson
lib/boson/scientist.rb
Boson.Scientist.analyze
def analyze(obj, command, args, &block) @global_options, @command, @original_args = {}, command, args.dup @args = translate_args(obj, args) return run_help_option(@command) if @global_options[:help] during_analyze(&block) rescue OptionParser::Error, Error raise if Boson.in_shell warn "Error: #{$!}" end
ruby
def analyze(obj, command, args, &block) @global_options, @command, @original_args = {}, command, args.dup @args = translate_args(obj, args) return run_help_option(@command) if @global_options[:help] during_analyze(&block) rescue OptionParser::Error, Error raise if Boson.in_shell warn "Error: #{$!}" end
[ "def", "analyze", "(", "obj", ",", "command", ",", "args", ",", "&", "block", ")", "@global_options", ",", "@command", ",", "@original_args", "=", "{", "}", ",", "command", ",", "args", ".", "dup", "@args", "=", "translate_args", "(", "obj", ",", "args", ")", "return", "run_help_option", "(", "@command", ")", "if", "@global_options", "[", ":help", "]", "during_analyze", "(", "block", ")", "rescue", "OptionParser", "::", "Error", ",", "Error", "raise", "if", "Boson", ".", "in_shell", "warn", "\"Error: #{$!}\"", "end" ]
Runs a command given its object and arguments
[ "Runs", "a", "command", "given", "its", "object", "and", "arguments" ]
17fe830fefd3dc41d90af01d191f074306591f32
https://github.com/cldwalker/boson/blob/17fe830fefd3dc41d90af01d191f074306591f32/lib/boson/scientist.rb#L103-L111
2,550
cldwalker/boson
lib/boson/option_parser.rb
Boson.OptionParser.formatted_usage
def formatted_usage return "" if @opt_types.empty? @opt_types.map do |opt, type| val = respond_to?("usage_for_#{type}", true) ? send("usage_for_#{type}", opt) : "#{opt}=:#{type}" "[" + val + "]" end.join(" ") end
ruby
def formatted_usage return "" if @opt_types.empty? @opt_types.map do |opt, type| val = respond_to?("usage_for_#{type}", true) ? send("usage_for_#{type}", opt) : "#{opt}=:#{type}" "[" + val + "]" end.join(" ") end
[ "def", "formatted_usage", "return", "\"\"", "if", "@opt_types", ".", "empty?", "@opt_types", ".", "map", "do", "|", "opt", ",", "type", "|", "val", "=", "respond_to?", "(", "\"usage_for_#{type}\"", ",", "true", ")", "?", "send", "(", "\"usage_for_#{type}\"", ",", "opt", ")", ":", "\"#{opt}=:#{type}\"", "\"[\"", "+", "val", "+", "\"]\"", "end", ".", "join", "(", "\" \"", ")", "end" ]
Generates one-line usage of all options.
[ "Generates", "one", "-", "line", "usage", "of", "all", "options", "." ]
17fe830fefd3dc41d90af01d191f074306591f32
https://github.com/cldwalker/boson/blob/17fe830fefd3dc41d90af01d191f074306591f32/lib/boson/option_parser.rb#L257-L264
2,551
cldwalker/boson
lib/boson/option_parser.rb
Boson.OptionParser.print_usage_table
def print_usage_table(options={}) fields = get_usage_fields options[:fields] fields, opts = get_fields_and_options(fields, options) render_table(fields, opts, options) end
ruby
def print_usage_table(options={}) fields = get_usage_fields options[:fields] fields, opts = get_fields_and_options(fields, options) render_table(fields, opts, options) end
[ "def", "print_usage_table", "(", "options", "=", "{", "}", ")", "fields", "=", "get_usage_fields", "options", "[", ":fields", "]", "fields", ",", "opts", "=", "get_fields_and_options", "(", "fields", ",", "options", ")", "render_table", "(", "fields", ",", "opts", ",", "options", ")", "end" ]
More verbose option help in the form of a table.
[ "More", "verbose", "option", "help", "in", "the", "form", "of", "a", "table", "." ]
17fe830fefd3dc41d90af01d191f074306591f32
https://github.com/cldwalker/boson/blob/17fe830fefd3dc41d90af01d191f074306591f32/lib/boson/option_parser.rb#L269-L273
2,552
cldwalker/boson
lib/boson/option_parser.rb
Boson.OptionParser.indifferent_hash
def indifferent_hash Hash.new {|hash,key| hash[key.to_sym] if String === key } end
ruby
def indifferent_hash Hash.new {|hash,key| hash[key.to_sym] if String === key } end
[ "def", "indifferent_hash", "Hash", ".", "new", "{", "|", "hash", ",", "key", "|", "hash", "[", "key", ".", "to_sym", "]", "if", "String", "===", "key", "}", "end" ]
Creates a Hash with indifferent access
[ "Creates", "a", "Hash", "with", "indifferent", "access" ]
17fe830fefd3dc41d90af01d191f074306591f32
https://github.com/cldwalker/boson/blob/17fe830fefd3dc41d90af01d191f074306591f32/lib/boson/option_parser.rb#L330-L332
2,553
cldwalker/boson
lib/boson/loader.rb
Boson.Loader.load
def load load_source_and_set_module module_callbacks if @module yield if block_given? # load dependencies detect_additions { load_commands } if load_commands? set_library_commands loaded_correctly? && (@loaded = true) end
ruby
def load load_source_and_set_module module_callbacks if @module yield if block_given? # load dependencies detect_additions { load_commands } if load_commands? set_library_commands loaded_correctly? && (@loaded = true) end
[ "def", "load", "load_source_and_set_module", "module_callbacks", "if", "@module", "yield", "if", "block_given?", "# load dependencies", "detect_additions", "{", "load_commands", "}", "if", "load_commands?", "set_library_commands", "loaded_correctly?", "&&", "(", "@loaded", "=", "true", ")", "end" ]
Loads a library and its dependencies and returns true if library loads correctly.
[ "Loads", "a", "library", "and", "its", "dependencies", "and", "returns", "true", "if", "library", "loads", "correctly", "." ]
17fe830fefd3dc41d90af01d191f074306591f32
https://github.com/cldwalker/boson/blob/17fe830fefd3dc41d90af01d191f074306591f32/lib/boson/loader.rb#L16-L23
2,554
cldwalker/boson
lib/boson/loader.rb
Boson.Loader.detect_additions
def detect_additions(options={}, &block) Util.detect(options, &block).tap do |detected| @commands.concat detected[:methods].map(&:to_s) end end
ruby
def detect_additions(options={}, &block) Util.detect(options, &block).tap do |detected| @commands.concat detected[:methods].map(&:to_s) end end
[ "def", "detect_additions", "(", "options", "=", "{", "}", ",", "&", "block", ")", "Util", ".", "detect", "(", "options", ",", "block", ")", ".", "tap", "do", "|", "detected", "|", "@commands", ".", "concat", "detected", "[", ":methods", "]", ".", "map", "(", ":to_s", ")", "end", "end" ]
Wraps around module loading for unexpected additions
[ "Wraps", "around", "module", "loading", "for", "unexpected", "additions" ]
17fe830fefd3dc41d90af01d191f074306591f32
https://github.com/cldwalker/boson/blob/17fe830fefd3dc41d90af01d191f074306591f32/lib/boson/loader.rb#L38-L42
2,555
cldwalker/boson
lib/boson/loader.rb
Boson.Loader.load_commands
def load_commands @module = @module ? Util.constantize(@module) : Util.create_module(Boson::Commands, clean_name) before_load_commands check_for_method_conflicts unless @force actual_load_commands rescue MethodConflictError => err handle_method_conflict_error err end
ruby
def load_commands @module = @module ? Util.constantize(@module) : Util.create_module(Boson::Commands, clean_name) before_load_commands check_for_method_conflicts unless @force actual_load_commands rescue MethodConflictError => err handle_method_conflict_error err end
[ "def", "load_commands", "@module", "=", "@module", "?", "Util", ".", "constantize", "(", "@module", ")", ":", "Util", ".", "create_module", "(", "Boson", "::", "Commands", ",", "clean_name", ")", "before_load_commands", "check_for_method_conflicts", "unless", "@force", "actual_load_commands", "rescue", "MethodConflictError", "=>", "err", "handle_method_conflict_error", "err", "end" ]
Prepares for command loading, loads commands and rescues certain errors.
[ "Prepares", "for", "command", "loading", "loads", "commands", "and", "rescues", "certain", "errors", "." ]
17fe830fefd3dc41d90af01d191f074306591f32
https://github.com/cldwalker/boson/blob/17fe830fefd3dc41d90af01d191f074306591f32/lib/boson/loader.rb#L45-L53
2,556
apiaryio/redsnow
lib/redsnow/object.rb
RedSnow.Object.deep_symbolize_keys
def deep_symbolize_keys return each_with_object({}) { |memo, (k, v)| memo[k.to_sym] = v.deep_symbolize_keys } if self.is_a?(Hash) return each_with_object([]) { |memo, v| memo << v.deep_symbolize_keys } if self.is_a?(Array) self end
ruby
def deep_symbolize_keys return each_with_object({}) { |memo, (k, v)| memo[k.to_sym] = v.deep_symbolize_keys } if self.is_a?(Hash) return each_with_object([]) { |memo, v| memo << v.deep_symbolize_keys } if self.is_a?(Array) self end
[ "def", "deep_symbolize_keys", "return", "each_with_object", "(", "{", "}", ")", "{", "|", "memo", ",", "(", "k", ",", "v", ")", "|", "memo", "[", "k", ".", "to_sym", "]", "=", "v", ".", "deep_symbolize_keys", "}", "if", "self", ".", "is_a?", "(", "Hash", ")", "return", "each_with_object", "(", "[", "]", ")", "{", "|", "memo", ",", "v", "|", "memo", "<<", "v", ".", "deep_symbolize_keys", "}", "if", "self", ".", "is_a?", "(", "Array", ")", "self", "end" ]
Symbolizes keys of a hash
[ "Symbolizes", "keys", "of", "a", "hash" ]
5a05b704218dfee6a73e066ca1e6924733b10bdc
https://github.com/apiaryio/redsnow/blob/5a05b704218dfee6a73e066ca1e6924733b10bdc/lib/redsnow/object.rb#L6-L10
2,557
apiaryio/redsnow
lib/redsnow/blueprint.rb
RedSnow.NamedBlueprintNode.ensure_description_newlines
def ensure_description_newlines(buffer) return if description.empty? if description[-1, 1] != '\n' buffer << '\n\n' elsif description.length > 1 && description[-2, 1] != '\n' buffer << '\n' end end
ruby
def ensure_description_newlines(buffer) return if description.empty? if description[-1, 1] != '\n' buffer << '\n\n' elsif description.length > 1 && description[-2, 1] != '\n' buffer << '\n' end end
[ "def", "ensure_description_newlines", "(", "buffer", ")", "return", "if", "description", ".", "empty?", "if", "description", "[", "-", "1", ",", "1", "]", "!=", "'\\n'", "buffer", "<<", "'\\n\\n'", "elsif", "description", ".", "length", ">", "1", "&&", "description", "[", "-", "2", ",", "1", "]", "!=", "'\\n'", "buffer", "<<", "'\\n'", "end", "end" ]
Ensure the input string buffer ends with two newlines. @param buffer [String] a buffer to check If the buffer does not ends with two newlines the newlines are added.
[ "Ensure", "the", "input", "string", "buffer", "ends", "with", "two", "newlines", "." ]
5a05b704218dfee6a73e066ca1e6924733b10bdc
https://github.com/apiaryio/redsnow/blob/5a05b704218dfee6a73e066ca1e6924733b10bdc/lib/redsnow/blueprint.rb#L40-L48
2,558
apiaryio/redsnow
lib/redsnow/blueprint.rb
RedSnow.KeyValueCollection.filter_collection
def filter_collection(ignore_keys) return @collection if ignore_keys.blank? @collection.select { |kv_item| !ignore_keys.include?(kv_item.keys.first) } end
ruby
def filter_collection(ignore_keys) return @collection if ignore_keys.blank? @collection.select { |kv_item| !ignore_keys.include?(kv_item.keys.first) } end
[ "def", "filter_collection", "(", "ignore_keys", ")", "return", "@collection", "if", "ignore_keys", ".", "blank?", "@collection", ".", "select", "{", "|", "kv_item", "|", "!", "ignore_keys", ".", "include?", "(", "kv_item", ".", "keys", ".", "first", ")", "}", "end" ]
Filter collection keys @return [Array<Hash>] collection without ignored keys
[ "Filter", "collection", "keys" ]
5a05b704218dfee6a73e066ca1e6924733b10bdc
https://github.com/apiaryio/redsnow/blob/5a05b704218dfee6a73e066ca1e6924733b10bdc/lib/redsnow/blueprint.rb#L70-L73
2,559
cldwalker/boson
lib/boson/library.rb
Boson.Library.command_objects
def command_objects(names=self.commands, command_array=Boson.commands) command_array.select {|e| names.include?(e.name) && e.lib == self.name } end
ruby
def command_objects(names=self.commands, command_array=Boson.commands) command_array.select {|e| names.include?(e.name) && e.lib == self.name } end
[ "def", "command_objects", "(", "names", "=", "self", ".", "commands", ",", "command_array", "=", "Boson", ".", "commands", ")", "command_array", ".", "select", "{", "|", "e", "|", "names", ".", "include?", "(", "e", ".", "name", ")", "&&", "e", ".", "lib", "==", "self", ".", "name", "}", "end" ]
Command objects of library's commands
[ "Command", "objects", "of", "library", "s", "commands" ]
17fe830fefd3dc41d90af01d191f074306591f32
https://github.com/cldwalker/boson/blob/17fe830fefd3dc41d90af01d191f074306591f32/lib/boson/library.rb#L91-L93
2,560
cldwalker/boson
lib/boson/util.rb
Boson.Util.create_module
def create_module(base_module, name) desired_class = camelize(name) possible_suffixes = [''] + %w{1 2 3 4 5 6 7 8 9 10} if suffix = possible_suffixes.find {|e| !base_module.const_defined?(desired_class+e) } base_module.const_set(desired_class+suffix, Module.new) end end
ruby
def create_module(base_module, name) desired_class = camelize(name) possible_suffixes = [''] + %w{1 2 3 4 5 6 7 8 9 10} if suffix = possible_suffixes.find {|e| !base_module.const_defined?(desired_class+e) } base_module.const_set(desired_class+suffix, Module.new) end end
[ "def", "create_module", "(", "base_module", ",", "name", ")", "desired_class", "=", "camelize", "(", "name", ")", "possible_suffixes", "=", "[", "''", "]", "+", "%w{", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "}", "if", "suffix", "=", "possible_suffixes", ".", "find", "{", "|", "e", "|", "!", "base_module", ".", "const_defined?", "(", "desired_class", "+", "e", ")", "}", "base_module", ".", "const_set", "(", "desired_class", "+", "suffix", ",", "Module", ".", "new", ")", "end", "end" ]
Creates a module under a given base module and possible name. If the module already exists, it attempts to create one with a number appended to the name.
[ "Creates", "a", "module", "under", "a", "given", "base", "module", "and", "possible", "name", ".", "If", "the", "module", "already", "exists", "it", "attempts", "to", "create", "one", "with", "a", "number", "appended", "to", "the", "name", "." ]
17fe830fefd3dc41d90af01d191f074306591f32
https://github.com/cldwalker/boson/blob/17fe830fefd3dc41d90af01d191f074306591f32/lib/boson/util.rb#L75-L82
2,561
sunny/handle_invalid_percent_encoding_requests
lib/handle_invalid_percent_encoding_requests/middleware.rb
HandleInvalidPercentEncodingRequests.Middleware.call
def call(env) # calling env.dup here prevents bad things from happening request = Rack::Request.new(env.dup) # calling request.params is sufficient to trigger the error see # https://github.com/rack/rack/issues/337#issuecomment-46453404 request.params @app.call(env) # Rescue from that specific ArgumentError rescue ArgumentError => e raise unless e.message =~ /invalid %-encoding/ @logger.info "Bad request. Returning 400 due to #{e.message} from " + \ "request with env #{request.inspect}" error_response end
ruby
def call(env) # calling env.dup here prevents bad things from happening request = Rack::Request.new(env.dup) # calling request.params is sufficient to trigger the error see # https://github.com/rack/rack/issues/337#issuecomment-46453404 request.params @app.call(env) # Rescue from that specific ArgumentError rescue ArgumentError => e raise unless e.message =~ /invalid %-encoding/ @logger.info "Bad request. Returning 400 due to #{e.message} from " + \ "request with env #{request.inspect}" error_response end
[ "def", "call", "(", "env", ")", "# calling env.dup here prevents bad things from happening", "request", "=", "Rack", "::", "Request", ".", "new", "(", "env", ".", "dup", ")", "# calling request.params is sufficient to trigger the error see", "# https://github.com/rack/rack/issues/337#issuecomment-46453404", "request", ".", "params", "@app", ".", "call", "(", "env", ")", "# Rescue from that specific ArgumentError", "rescue", "ArgumentError", "=>", "e", "raise", "unless", "e", ".", "message", "=~", "/", "/", "@logger", ".", "info", "\"Bad request. Returning 400 due to #{e.message} from \"", "+", "\"request with env #{request.inspect}\"", "error_response", "end" ]
Called by Rack when a request comes through
[ "Called", "by", "Rack", "when", "a", "request", "comes", "through" ]
eafa7d0c867a015f865b1242af3940dc7536e575
https://github.com/sunny/handle_invalid_percent_encoding_requests/blob/eafa7d0c867a015f865b1242af3940dc7536e575/lib/handle_invalid_percent_encoding_requests/middleware.rb#L13-L29
2,562
monkbroc/particlerb
lib/particle/connection.rb
Particle.Connection.connection
def connection @connection ||= Faraday.new(conn_opts) do |http| http.url_prefix = endpoint if @access_token http.authorization :Bearer, @access_token end end end
ruby
def connection @connection ||= Faraday.new(conn_opts) do |http| http.url_prefix = endpoint if @access_token http.authorization :Bearer, @access_token end end end
[ "def", "connection", "@connection", "||=", "Faraday", ".", "new", "(", "conn_opts", ")", "do", "|", "http", "|", "http", ".", "url_prefix", "=", "endpoint", "if", "@access_token", "http", ".", "authorization", ":Bearer", ",", "@access_token", "end", "end", "end" ]
HTTP connection for the Particle API @return [Faraday::Connection]
[ "HTTP", "connection", "for", "the", "Particle", "API" ]
a76ef290fd60cf216352f70fc47cb6109ce70742
https://github.com/monkbroc/particlerb/blob/a76ef290fd60cf216352f70fc47cb6109ce70742/lib/particle/connection.rb#L70-L77
2,563
cldwalker/boson
lib/boson/method_inspector.rb
Boson.MethodInspector.new_method_added
def new_method_added(mod, meth) self.current_module = mod store[:temp] ||= {} METHODS.each do |e| store[e][meth.to_s] = store[:temp][e] if store[:temp][e] end if store[:temp][:option] (store[:options][meth.to_s] ||= {}).merge! store[:temp][:option] end during_new_method_added mod, meth store[:temp] = {} if SCRAPEABLE_METHODS.any? {|m| has_inspector_method?(meth, m) } set_arguments(mod, meth) end end
ruby
def new_method_added(mod, meth) self.current_module = mod store[:temp] ||= {} METHODS.each do |e| store[e][meth.to_s] = store[:temp][e] if store[:temp][e] end if store[:temp][:option] (store[:options][meth.to_s] ||= {}).merge! store[:temp][:option] end during_new_method_added mod, meth store[:temp] = {} if SCRAPEABLE_METHODS.any? {|m| has_inspector_method?(meth, m) } set_arguments(mod, meth) end end
[ "def", "new_method_added", "(", "mod", ",", "meth", ")", "self", ".", "current_module", "=", "mod", "store", "[", ":temp", "]", "||=", "{", "}", "METHODS", ".", "each", "do", "|", "e", "|", "store", "[", "e", "]", "[", "meth", ".", "to_s", "]", "=", "store", "[", ":temp", "]", "[", "e", "]", "if", "store", "[", ":temp", "]", "[", "e", "]", "end", "if", "store", "[", ":temp", "]", "[", ":option", "]", "(", "store", "[", ":options", "]", "[", "meth", ".", "to_s", "]", "||=", "{", "}", ")", ".", "merge!", "store", "[", ":temp", "]", "[", ":option", "]", "end", "during_new_method_added", "mod", ",", "meth", "store", "[", ":temp", "]", "=", "{", "}", "if", "SCRAPEABLE_METHODS", ".", "any?", "{", "|", "m", "|", "has_inspector_method?", "(", "meth", ",", "m", ")", "}", "set_arguments", "(", "mod", ",", "meth", ")", "end", "end" ]
The method_added used while scraping method attributes.
[ "The", "method_added", "used", "while", "scraping", "method", "attributes", "." ]
17fe830fefd3dc41d90af01d191f074306591f32
https://github.com/cldwalker/boson/blob/17fe830fefd3dc41d90af01d191f074306591f32/lib/boson/method_inspector.rb#L37-L53
2,564
cldwalker/boson
lib/boson/option_command.rb
Boson.OptionCommand.parse
def parse(args) if args.size == 1 && args[0].is_a?(String) args = Shellwords.shellwords(args[0]) if !Boson.in_shell global_opt, parsed_options, args = parse_options args # last string argument interpreted as args + options elsif args.size > 1 && args[-1].is_a?(String) temp_args = Boson.in_shell ? args : Shellwords.shellwords(args.pop) global_opt, parsed_options, new_args = parse_options temp_args Boson.in_shell ? args = new_args : args += new_args # add default options elsif @command.options.nil? || @command.options.empty? || (@command.numerical_arg_size? && args.size <= (@command.arg_size - 1).abs) || (@command.has_splat_args? && !args[-1].is_a?(Hash)) global_opt, parsed_options = parse_options([])[0,2] # merge default options with given hash of options elsif (@command.has_splat_args? || (args.size == @command.arg_size)) && args[-1].is_a?(Hash) global_opt, parsed_options = parse_options([])[0,2] parsed_options.merge!(args.pop) end [global_opt || {}, parsed_options, args] end
ruby
def parse(args) if args.size == 1 && args[0].is_a?(String) args = Shellwords.shellwords(args[0]) if !Boson.in_shell global_opt, parsed_options, args = parse_options args # last string argument interpreted as args + options elsif args.size > 1 && args[-1].is_a?(String) temp_args = Boson.in_shell ? args : Shellwords.shellwords(args.pop) global_opt, parsed_options, new_args = parse_options temp_args Boson.in_shell ? args = new_args : args += new_args # add default options elsif @command.options.nil? || @command.options.empty? || (@command.numerical_arg_size? && args.size <= (@command.arg_size - 1).abs) || (@command.has_splat_args? && !args[-1].is_a?(Hash)) global_opt, parsed_options = parse_options([])[0,2] # merge default options with given hash of options elsif (@command.has_splat_args? || (args.size == @command.arg_size)) && args[-1].is_a?(Hash) global_opt, parsed_options = parse_options([])[0,2] parsed_options.merge!(args.pop) end [global_opt || {}, parsed_options, args] end
[ "def", "parse", "(", "args", ")", "if", "args", ".", "size", "==", "1", "&&", "args", "[", "0", "]", ".", "is_a?", "(", "String", ")", "args", "=", "Shellwords", ".", "shellwords", "(", "args", "[", "0", "]", ")", "if", "!", "Boson", ".", "in_shell", "global_opt", ",", "parsed_options", ",", "args", "=", "parse_options", "args", "# last string argument interpreted as args + options", "elsif", "args", ".", "size", ">", "1", "&&", "args", "[", "-", "1", "]", ".", "is_a?", "(", "String", ")", "temp_args", "=", "Boson", ".", "in_shell", "?", "args", ":", "Shellwords", ".", "shellwords", "(", "args", ".", "pop", ")", "global_opt", ",", "parsed_options", ",", "new_args", "=", "parse_options", "temp_args", "Boson", ".", "in_shell", "?", "args", "=", "new_args", ":", "args", "+=", "new_args", "# add default options", "elsif", "@command", ".", "options", ".", "nil?", "||", "@command", ".", "options", ".", "empty?", "||", "(", "@command", ".", "numerical_arg_size?", "&&", "args", ".", "size", "<=", "(", "@command", ".", "arg_size", "-", "1", ")", ".", "abs", ")", "||", "(", "@command", ".", "has_splat_args?", "&&", "!", "args", "[", "-", "1", "]", ".", "is_a?", "(", "Hash", ")", ")", "global_opt", ",", "parsed_options", "=", "parse_options", "(", "[", "]", ")", "[", "0", ",", "2", "]", "# merge default options with given hash of options", "elsif", "(", "@command", ".", "has_splat_args?", "||", "(", "args", ".", "size", "==", "@command", ".", "arg_size", ")", ")", "&&", "args", "[", "-", "1", "]", ".", "is_a?", "(", "Hash", ")", "global_opt", ",", "parsed_options", "=", "parse_options", "(", "[", "]", ")", "[", "0", ",", "2", "]", "parsed_options", ".", "merge!", "(", "args", ".", "pop", ")", "end", "[", "global_opt", "||", "{", "}", ",", "parsed_options", ",", "args", "]", "end" ]
Parses arguments and returns global options, local options and leftover arguments.
[ "Parses", "arguments", "and", "returns", "global", "options", "local", "options", "and", "leftover", "arguments", "." ]
17fe830fefd3dc41d90af01d191f074306591f32
https://github.com/cldwalker/boson/blob/17fe830fefd3dc41d90af01d191f074306591f32/lib/boson/option_command.rb#L43-L64
2,565
cldwalker/boson
lib/boson/option_command.rb
Boson.OptionCommand.modify_args
def modify_args(args) if @command.default_option && @command.numerical_arg_size? && @command.arg_size <= 1 && !args[0].is_a?(Hash) && args[0].to_s[/./] != '-' && !args.join.empty? args[0] = "--#{@command.default_option}=#{args[0]}" end end
ruby
def modify_args(args) if @command.default_option && @command.numerical_arg_size? && @command.arg_size <= 1 && !args[0].is_a?(Hash) && args[0].to_s[/./] != '-' && !args.join.empty? args[0] = "--#{@command.default_option}=#{args[0]}" end end
[ "def", "modify_args", "(", "args", ")", "if", "@command", ".", "default_option", "&&", "@command", ".", "numerical_arg_size?", "&&", "@command", ".", "arg_size", "<=", "1", "&&", "!", "args", "[", "0", "]", ".", "is_a?", "(", "Hash", ")", "&&", "args", "[", "0", "]", ".", "to_s", "[", "/", "/", "]", "!=", "'-'", "&&", "!", "args", ".", "join", ".", "empty?", "args", "[", "0", "]", "=", "\"--#{@command.default_option}=#{args[0]}\"", "end", "end" ]
modifies args for edge cases
[ "modifies", "args", "for", "edge", "cases" ]
17fe830fefd3dc41d90af01d191f074306591f32
https://github.com/cldwalker/boson/blob/17fe830fefd3dc41d90af01d191f074306591f32/lib/boson/option_command.rb#L79-L85
2,566
cldwalker/boson
lib/boson/option_command.rb
Boson.OptionCommand.check_argument_size
def check_argument_size(args) if @command.numerical_arg_size? && args.size != @command.arg_size command_size, args_size = args.size > @command.arg_size ? [@command.arg_size, args.size] : [@command.arg_size - 1, args.size - 1] raise CommandArgumentError, "wrong number of arguments (#{args_size} for #{command_size})" end end
ruby
def check_argument_size(args) if @command.numerical_arg_size? && args.size != @command.arg_size command_size, args_size = args.size > @command.arg_size ? [@command.arg_size, args.size] : [@command.arg_size - 1, args.size - 1] raise CommandArgumentError, "wrong number of arguments (#{args_size} for #{command_size})" end end
[ "def", "check_argument_size", "(", "args", ")", "if", "@command", ".", "numerical_arg_size?", "&&", "args", ".", "size", "!=", "@command", ".", "arg_size", "command_size", ",", "args_size", "=", "args", ".", "size", ">", "@command", ".", "arg_size", "?", "[", "@command", ".", "arg_size", ",", "args", ".", "size", "]", ":", "[", "@command", ".", "arg_size", "-", "1", ",", "args", ".", "size", "-", "1", "]", "raise", "CommandArgumentError", ",", "\"wrong number of arguments (#{args_size} for #{command_size})\"", "end", "end" ]
raises CommandArgumentError if argument size is incorrect for given args
[ "raises", "CommandArgumentError", "if", "argument", "size", "is", "incorrect", "for", "given", "args" ]
17fe830fefd3dc41d90af01d191f074306591f32
https://github.com/cldwalker/boson/blob/17fe830fefd3dc41d90af01d191f074306591f32/lib/boson/option_command.rb#L88-L96
2,567
cldwalker/boson
lib/boson/option_command.rb
Boson.OptionCommand.add_default_args
def add_default_args(args, obj) if @command.args && args.size < @command.arg_size - 1 # leave off last arg since its an option @command.args.slice(0..-2).each_with_index {|arr,i| next if args.size >= i + 1 # only fill in once args run out break if arr.size != 2 # a default arg value must exist begin args[i] = @command.file_parsed_args ? obj.instance_eval(arr[1]) : arr[1] rescue Exception raise Scientist::Error, "Unable to set default argument at " + "position #{i+1}.\nReason: #{$!.message}" end } end end
ruby
def add_default_args(args, obj) if @command.args && args.size < @command.arg_size - 1 # leave off last arg since its an option @command.args.slice(0..-2).each_with_index {|arr,i| next if args.size >= i + 1 # only fill in once args run out break if arr.size != 2 # a default arg value must exist begin args[i] = @command.file_parsed_args ? obj.instance_eval(arr[1]) : arr[1] rescue Exception raise Scientist::Error, "Unable to set default argument at " + "position #{i+1}.\nReason: #{$!.message}" end } end end
[ "def", "add_default_args", "(", "args", ",", "obj", ")", "if", "@command", ".", "args", "&&", "args", ".", "size", "<", "@command", ".", "arg_size", "-", "1", "# leave off last arg since its an option", "@command", ".", "args", ".", "slice", "(", "0", "..", "-", "2", ")", ".", "each_with_index", "{", "|", "arr", ",", "i", "|", "next", "if", "args", ".", "size", ">=", "i", "+", "1", "# only fill in once args run out", "break", "if", "arr", ".", "size", "!=", "2", "# a default arg value must exist", "begin", "args", "[", "i", "]", "=", "@command", ".", "file_parsed_args", "?", "obj", ".", "instance_eval", "(", "arr", "[", "1", "]", ")", ":", "arr", "[", "1", "]", "rescue", "Exception", "raise", "Scientist", "::", "Error", ",", "\"Unable to set default argument at \"", "+", "\"position #{i+1}.\\nReason: #{$!.message}\"", "end", "}", "end", "end" ]
Adds default args as original method would
[ "Adds", "default", "args", "as", "original", "method", "would" ]
17fe830fefd3dc41d90af01d191f074306591f32
https://github.com/cldwalker/boson/blob/17fe830fefd3dc41d90af01d191f074306591f32/lib/boson/option_command.rb#L99-L113
2,568
alfa-jpn/kakurenbo
lib/kakurenbo/core.rb
Kakurenbo.Core.delete
def delete(options = {:hard => false}) if options[:hard] self.class.delete(self.id, options) else return if new_record? or destroyed? update_column kakurenbo_column, current_time_from_proper_timezone end end
ruby
def delete(options = {:hard => false}) if options[:hard] self.class.delete(self.id, options) else return if new_record? or destroyed? update_column kakurenbo_column, current_time_from_proper_timezone end end
[ "def", "delete", "(", "options", "=", "{", ":hard", "=>", "false", "}", ")", "if", "options", "[", ":hard", "]", "self", ".", "class", ".", "delete", "(", "self", ".", "id", ",", "options", ")", "else", "return", "if", "new_record?", "or", "destroyed?", "update_column", "kakurenbo_column", ",", "current_time_from_proper_timezone", "end", "end" ]
delete record. @param options [Hash] options. @option options [Boolean] hard (false) if hard-delete.
[ "delete", "record", "." ]
d577f885134f8229c926a60af8dbe7adabd810d8
https://github.com/alfa-jpn/kakurenbo/blob/d577f885134f8229c926a60af8dbe7adabd810d8/lib/kakurenbo/core.rb#L57-L64
2,569
alfa-jpn/kakurenbo
lib/kakurenbo/core.rb
Kakurenbo.Core.destroy
def destroy(options = {:hard => false}) if options[:hard] with_transaction_returning_status do hard_destroy_associated_records self.reload.hard_destroy end else return true if destroyed? with_transaction_returning_status do destroy_at = Time.now run_callbacks(:destroy){ update_column kakurenbo_column, destroy_at; self } end end end
ruby
def destroy(options = {:hard => false}) if options[:hard] with_transaction_returning_status do hard_destroy_associated_records self.reload.hard_destroy end else return true if destroyed? with_transaction_returning_status do destroy_at = Time.now run_callbacks(:destroy){ update_column kakurenbo_column, destroy_at; self } end end end
[ "def", "destroy", "(", "options", "=", "{", ":hard", "=>", "false", "}", ")", "if", "options", "[", ":hard", "]", "with_transaction_returning_status", "do", "hard_destroy_associated_records", "self", ".", "reload", ".", "hard_destroy", "end", "else", "return", "true", "if", "destroyed?", "with_transaction_returning_status", "do", "destroy_at", "=", "Time", ".", "now", "run_callbacks", "(", ":destroy", ")", "{", "update_column", "kakurenbo_column", ",", "destroy_at", ";", "self", "}", "end", "end", "end" ]
destroy record and run callbacks. @param options [Hash] options. @option options [Boolean] hard (false) if hard-delete. @return [Boolean, self] if action is cancelled, return false.
[ "destroy", "record", "and", "run", "callbacks", "." ]
d577f885134f8229c926a60af8dbe7adabd810d8
https://github.com/alfa-jpn/kakurenbo/blob/d577f885134f8229c926a60af8dbe7adabd810d8/lib/kakurenbo/core.rb#L72-L85
2,570
alfa-jpn/kakurenbo
lib/kakurenbo/core.rb
Kakurenbo.Core.restore
def restore(options = {:recursive => true}) return false unless destroyed? with_transaction_returning_status do run_callbacks(:restore) do restore_associated_records if options[:recursive] update_column kakurenbo_column, nil self end end end
ruby
def restore(options = {:recursive => true}) return false unless destroyed? with_transaction_returning_status do run_callbacks(:restore) do restore_associated_records if options[:recursive] update_column kakurenbo_column, nil self end end end
[ "def", "restore", "(", "options", "=", "{", ":recursive", "=>", "true", "}", ")", "return", "false", "unless", "destroyed?", "with_transaction_returning_status", "do", "run_callbacks", "(", ":restore", ")", "do", "restore_associated_records", "if", "options", "[", ":recursive", "]", "update_column", "kakurenbo_column", ",", "nil", "self", "end", "end", "end" ]
restore record. @param options [Hash] options. @option options [Boolean] recursive (true) if restore recursive. @return [Boolean, self] if action is cancelled, return false.
[ "restore", "record", "." ]
d577f885134f8229c926a60af8dbe7adabd810d8
https://github.com/alfa-jpn/kakurenbo/blob/d577f885134f8229c926a60af8dbe7adabd810d8/lib/kakurenbo/core.rb#L119-L129
2,571
alfa-jpn/kakurenbo
lib/kakurenbo/core.rb
Kakurenbo.Core.dependent_association_scopes
def dependent_association_scopes self.class.reflect_on_all_associations.select { |reflection| reflection.options[:dependent] == :destroy and reflection.klass.paranoid? }.map { |reflection| self.association(reflection.name).tap {|assoc| assoc.reset_scope }.scope } end
ruby
def dependent_association_scopes self.class.reflect_on_all_associations.select { |reflection| reflection.options[:dependent] == :destroy and reflection.klass.paranoid? }.map { |reflection| self.association(reflection.name).tap {|assoc| assoc.reset_scope }.scope } end
[ "def", "dependent_association_scopes", "self", ".", "class", ".", "reflect_on_all_associations", ".", "select", "{", "|", "reflection", "|", "reflection", ".", "options", "[", ":dependent", "]", "==", ":destroy", "and", "reflection", ".", "klass", ".", "paranoid?", "}", ".", "map", "{", "|", "reflection", "|", "self", ".", "association", "(", "reflection", ".", "name", ")", ".", "tap", "{", "|", "assoc", "|", "assoc", ".", "reset_scope", "}", ".", "scope", "}", "end" ]
All Scope of dependent association. @return [Array<ActiveRecord::Relation>] array of dependent association.
[ "All", "Scope", "of", "dependent", "association", "." ]
d577f885134f8229c926a60af8dbe7adabd810d8
https://github.com/alfa-jpn/kakurenbo/blob/d577f885134f8229c926a60af8dbe7adabd810d8/lib/kakurenbo/core.rb#L145-L151
2,572
schleyfox/ruby_kml
lib/kml/geometry.rb
KML.Geometry.altitude_mode=
def altitude_mode=(mode) allowed_modes = %w(clampToGround relativeToGround absolute) if allowed_modes.include?(mode) @altitude_mode = mode else raise ArgumentError, "Must be one of the allowed altitude modes: #{allowed_modes.join(',')}" end end
ruby
def altitude_mode=(mode) allowed_modes = %w(clampToGround relativeToGround absolute) if allowed_modes.include?(mode) @altitude_mode = mode else raise ArgumentError, "Must be one of the allowed altitude modes: #{allowed_modes.join(',')}" end end
[ "def", "altitude_mode", "=", "(", "mode", ")", "allowed_modes", "=", "%w(", "clampToGround", "relativeToGround", "absolute", ")", "if", "allowed_modes", ".", "include?", "(", "mode", ")", "@altitude_mode", "=", "mode", "else", "raise", "ArgumentError", ",", "\"Must be one of the allowed altitude modes: #{allowed_modes.join(',')}\"", "end", "end" ]
Set the altitude mode
[ "Set", "the", "altitude", "mode" ]
0d6b4d076e1ee155893f7d8e82b7055644e024b8
https://github.com/schleyfox/ruby_kml/blob/0d6b4d076e1ee155893f7d8e82b7055644e024b8/lib/kml/geometry.rb#L63-L70
2,573
schleyfox/ruby_kml
lib/kml/feature.rb
KML.Feature.render
def render(xm=Builder::XmlMarkup.new(:indent => 2)) [:name, :visibility, :address].each do |a| xm.__send__(a, self.__send__(a)) unless self.__send__(a).nil? end xm.description { xm.cdata!(description) } unless description.nil? xm.open(self.open) unless open.nil? xm.phoneNumber(phone_number) unless phone_number.nil? xm.styleUrl(style_url) unless style_url.nil? unless address_details.nil? xm.AddressDetails(:xmlns => "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0") { address_details.render(xm) } end xm.Snippet(snippet.text, snippet.max_lines) unless snippet.nil? xm.LookAt { look_at.render(xm) } unless look_at.nil? xm.TimePrimitive { time_primitive.render(xm) } unless time_primitive.nil? xm.StyleSelector { style_selector.render(xm) } unless style_selector.nil? end
ruby
def render(xm=Builder::XmlMarkup.new(:indent => 2)) [:name, :visibility, :address].each do |a| xm.__send__(a, self.__send__(a)) unless self.__send__(a).nil? end xm.description { xm.cdata!(description) } unless description.nil? xm.open(self.open) unless open.nil? xm.phoneNumber(phone_number) unless phone_number.nil? xm.styleUrl(style_url) unless style_url.nil? unless address_details.nil? xm.AddressDetails(:xmlns => "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0") { address_details.render(xm) } end xm.Snippet(snippet.text, snippet.max_lines) unless snippet.nil? xm.LookAt { look_at.render(xm) } unless look_at.nil? xm.TimePrimitive { time_primitive.render(xm) } unless time_primitive.nil? xm.StyleSelector { style_selector.render(xm) } unless style_selector.nil? end
[ "def", "render", "(", "xm", "=", "Builder", "::", "XmlMarkup", ".", "new", "(", ":indent", "=>", "2", ")", ")", "[", ":name", ",", ":visibility", ",", ":address", "]", ".", "each", "do", "|", "a", "|", "xm", ".", "__send__", "(", "a", ",", "self", ".", "__send__", "(", "a", ")", ")", "unless", "self", ".", "__send__", "(", "a", ")", ".", "nil?", "end", "xm", ".", "description", "{", "xm", ".", "cdata!", "(", "description", ")", "}", "unless", "description", ".", "nil?", "xm", ".", "open", "(", "self", ".", "open", ")", "unless", "open", ".", "nil?", "xm", ".", "phoneNumber", "(", "phone_number", ")", "unless", "phone_number", ".", "nil?", "xm", ".", "styleUrl", "(", "style_url", ")", "unless", "style_url", ".", "nil?", "unless", "address_details", ".", "nil?", "xm", ".", "AddressDetails", "(", ":xmlns", "=>", "\"urn:oasis:names:tc:ciq:xsdschema:xAL:2.0\"", ")", "{", "address_details", ".", "render", "(", "xm", ")", "}", "end", "xm", ".", "Snippet", "(", "snippet", ".", "text", ",", "snippet", ".", "max_lines", ")", "unless", "snippet", ".", "nil?", "xm", ".", "LookAt", "{", "look_at", ".", "render", "(", "xm", ")", "}", "unless", "look_at", ".", "nil?", "xm", ".", "TimePrimitive", "{", "time_primitive", ".", "render", "(", "xm", ")", "}", "unless", "time_primitive", ".", "nil?", "xm", ".", "StyleSelector", "{", "style_selector", ".", "render", "(", "xm", ")", "}", "unless", "style_selector", ".", "nil?", "end" ]
Render the object and all of its sub-elements.
[ "Render", "the", "object", "and", "all", "of", "its", "sub", "-", "elements", "." ]
0d6b4d076e1ee155893f7d8e82b7055644e024b8
https://github.com/schleyfox/ruby_kml/blob/0d6b4d076e1ee155893f7d8e82b7055644e024b8/lib/kml/feature.rb#L133-L153
2,574
taxweb/ransack_advanced_search
app/controllers/concerns/ransack_advanced_search/saved_search_utils.rb
RansackAdvancedSearch.SavedSearchUtils.perform_saved_searches_actions
def perform_saved_searches_actions(context, params={}) get_saved_searches(context) save_or_update_saved_search(params.merge(context: context)) get_params_to_search(context) end
ruby
def perform_saved_searches_actions(context, params={}) get_saved_searches(context) save_or_update_saved_search(params.merge(context: context)) get_params_to_search(context) end
[ "def", "perform_saved_searches_actions", "(", "context", ",", "params", "=", "{", "}", ")", "get_saved_searches", "(", "context", ")", "save_or_update_saved_search", "(", "params", ".", "merge", "(", "context", ":", "context", ")", ")", "get_params_to_search", "(", "context", ")", "end" ]
Perform saved searches actions to provide full functionality with one method
[ "Perform", "saved", "searches", "actions", "to", "provide", "full", "functionality", "with", "one", "method" ]
1e757ad118aa02bd9064fa02fca48d32163fcd87
https://github.com/taxweb/ransack_advanced_search/blob/1e757ad118aa02bd9064fa02fca48d32163fcd87/app/controllers/concerns/ransack_advanced_search/saved_search_utils.rb#L6-L10
2,575
taxweb/ransack_advanced_search
app/controllers/concerns/ransack_advanced_search/saved_search_utils.rb
RansackAdvancedSearch.SavedSearchUtils.get_params_to_search
def get_params_to_search(context) if params[:saved_search].present? @saved_search = SavedSearch.find_by(id: params[:saved_search], context: context) end return params[:q] if params[:use_search_params].present? params[:q] = @saved_search.try(:search_params) || params[:q] end
ruby
def get_params_to_search(context) if params[:saved_search].present? @saved_search = SavedSearch.find_by(id: params[:saved_search], context: context) end return params[:q] if params[:use_search_params].present? params[:q] = @saved_search.try(:search_params) || params[:q] end
[ "def", "get_params_to_search", "(", "context", ")", "if", "params", "[", ":saved_search", "]", ".", "present?", "@saved_search", "=", "SavedSearch", ".", "find_by", "(", "id", ":", "params", "[", ":saved_search", "]", ",", "context", ":", "context", ")", "end", "return", "params", "[", ":q", "]", "if", "params", "[", ":use_search_params", "]", ".", "present?", "params", "[", ":q", "]", "=", "@saved_search", ".", "try", "(", ":search_params", ")", "||", "params", "[", ":q", "]", "end" ]
Return params of Saved Search or search form params
[ "Return", "params", "of", "Saved", "Search", "or", "search", "form", "params" ]
1e757ad118aa02bd9064fa02fca48d32163fcd87
https://github.com/taxweb/ransack_advanced_search/blob/1e757ad118aa02bd9064fa02fca48d32163fcd87/app/controllers/concerns/ransack_advanced_search/saved_search_utils.rb#L18-L24
2,576
taxweb/ransack_advanced_search
app/controllers/concerns/ransack_advanced_search/saved_search_utils.rb
RansackAdvancedSearch.SavedSearchUtils.save_or_update_saved_search
def save_or_update_saved_search(params) if params[:save_new_search].present? || params[:save_search].present? if params[:save_new_search].present? @saved_search = new_saved_search(params) elsif params[:save_search].present? && params[:saved_search].present? @saved_search = update_saved_search(params) elsif params[:save_search].present? @saved_search = new_saved_search(params) end if @saved_search.save flash[:notice] = t('ransack.saved_search.save.success') else flash[:error] = t('ransack.saved_search.save.error') end end end
ruby
def save_or_update_saved_search(params) if params[:save_new_search].present? || params[:save_search].present? if params[:save_new_search].present? @saved_search = new_saved_search(params) elsif params[:save_search].present? && params[:saved_search].present? @saved_search = update_saved_search(params) elsif params[:save_search].present? @saved_search = new_saved_search(params) end if @saved_search.save flash[:notice] = t('ransack.saved_search.save.success') else flash[:error] = t('ransack.saved_search.save.error') end end end
[ "def", "save_or_update_saved_search", "(", "params", ")", "if", "params", "[", ":save_new_search", "]", ".", "present?", "||", "params", "[", ":save_search", "]", ".", "present?", "if", "params", "[", ":save_new_search", "]", ".", "present?", "@saved_search", "=", "new_saved_search", "(", "params", ")", "elsif", "params", "[", ":save_search", "]", ".", "present?", "&&", "params", "[", ":saved_search", "]", ".", "present?", "@saved_search", "=", "update_saved_search", "(", "params", ")", "elsif", "params", "[", ":save_search", "]", ".", "present?", "@saved_search", "=", "new_saved_search", "(", "params", ")", "end", "if", "@saved_search", ".", "save", "flash", "[", ":notice", "]", "=", "t", "(", "'ransack.saved_search.save.success'", ")", "else", "flash", "[", ":error", "]", "=", "t", "(", "'ransack.saved_search.save.error'", ")", "end", "end", "end" ]
Save or update Saved Search
[ "Save", "or", "update", "Saved", "Search" ]
1e757ad118aa02bd9064fa02fca48d32163fcd87
https://github.com/taxweb/ransack_advanced_search/blob/1e757ad118aa02bd9064fa02fca48d32163fcd87/app/controllers/concerns/ransack_advanced_search/saved_search_utils.rb#L27-L43
2,577
gderosa/rubysu
lib/sudo/wrapper.rb
Sudo.Wrapper.start!
def start! Sudo::System.check @sudo_pid = spawn( "#{SUDO_CMD} -E #{RUBY_CMD} -I#{LIBDIR} #{@ruby_opts} #{SERVER_SCRIPT} #{@socket} #{Process.uid}" ) Process.detach(@sudo_pid) if @sudo_pid # avoid zombies finalizer = Finalizer.new(pid: @sudo_pid, socket: @socket) ObjectSpace.define_finalizer(self, finalizer) if wait_for(timeout: 1){File.exists? @socket} @proxy = DRbObject.new_with_uri(server_uri) else raise RuntimeError, "Couldn't create DRb socket #{@socket}" end load! self end
ruby
def start! Sudo::System.check @sudo_pid = spawn( "#{SUDO_CMD} -E #{RUBY_CMD} -I#{LIBDIR} #{@ruby_opts} #{SERVER_SCRIPT} #{@socket} #{Process.uid}" ) Process.detach(@sudo_pid) if @sudo_pid # avoid zombies finalizer = Finalizer.new(pid: @sudo_pid, socket: @socket) ObjectSpace.define_finalizer(self, finalizer) if wait_for(timeout: 1){File.exists? @socket} @proxy = DRbObject.new_with_uri(server_uri) else raise RuntimeError, "Couldn't create DRb socket #{@socket}" end load! self end
[ "def", "start!", "Sudo", "::", "System", ".", "check", "@sudo_pid", "=", "spawn", "(", "\"#{SUDO_CMD} -E #{RUBY_CMD} -I#{LIBDIR} #{@ruby_opts} #{SERVER_SCRIPT} #{@socket} #{Process.uid}\"", ")", "Process", ".", "detach", "(", "@sudo_pid", ")", "if", "@sudo_pid", "# avoid zombies", "finalizer", "=", "Finalizer", ".", "new", "(", "pid", ":", "@sudo_pid", ",", "socket", ":", "@socket", ")", "ObjectSpace", ".", "define_finalizer", "(", "self", ",", "finalizer", ")", "if", "wait_for", "(", "timeout", ":", "1", ")", "{", "File", ".", "exists?", "@socket", "}", "@proxy", "=", "DRbObject", ".", "new_with_uri", "(", "server_uri", ")", "else", "raise", "RuntimeError", ",", "\"Couldn't create DRb socket #{@socket}\"", "end", "load!", "self", "end" ]
Start the sudo-ed Ruby process.
[ "Start", "the", "sudo", "-", "ed", "Ruby", "process", "." ]
8a2905c659b3bb0ec408c6f5283596bc622d2d19
https://github.com/gderosa/rubysu/blob/8a2905c659b3bb0ec408c6f5283596bc622d2d19/lib/sudo/wrapper.rb#L62-L81
2,578
gderosa/rubysu
lib/sudo/wrapper.rb
Sudo.Wrapper.load_gems
def load_gems load_paths prospective_gems.each do |prospect| gem_name = prospect.dup begin loaded = @proxy.proxy(Kernel, :require, gem_name) # puts "Loading Gem: #{gem_name} => #{loaded}" rescue LoadError, NameError => e old_gem_name = gem_name.dup gem_name.gsub!('-', '/') retry if old_gem_name != gem_name end end end
ruby
def load_gems load_paths prospective_gems.each do |prospect| gem_name = prospect.dup begin loaded = @proxy.proxy(Kernel, :require, gem_name) # puts "Loading Gem: #{gem_name} => #{loaded}" rescue LoadError, NameError => e old_gem_name = gem_name.dup gem_name.gsub!('-', '/') retry if old_gem_name != gem_name end end end
[ "def", "load_gems", "load_paths", "prospective_gems", ".", "each", "do", "|", "prospect", "|", "gem_name", "=", "prospect", ".", "dup", "begin", "loaded", "=", "@proxy", ".", "proxy", "(", "Kernel", ",", ":require", ",", "gem_name", ")", "# puts \"Loading Gem: #{gem_name} => #{loaded}\"", "rescue", "LoadError", ",", "NameError", "=>", "e", "old_gem_name", "=", "gem_name", ".", "dup", "gem_name", ".", "gsub!", "(", "'-'", ",", "'/'", ")", "retry", "if", "old_gem_name", "!=", "gem_name", "end", "end", "end" ]
Load needed libraries in the DRb server. Usually you don't need
[ "Load", "needed", "libraries", "in", "the", "DRb", "server", ".", "Usually", "you", "don", "t", "need" ]
8a2905c659b3bb0ec408c6f5283596bc622d2d19
https://github.com/gderosa/rubysu/blob/8a2905c659b3bb0ec408c6f5283596bc622d2d19/lib/sudo/wrapper.rb#L137-L150
2,579
bdwyertech/chef-rundeck2
lib/chef-rundeck/config.rb
ChefRunDeck.Config.add
def add(config = {}) config.each do |key, value| define_setting key.to_sym, value end end
ruby
def add(config = {}) config.each do |key, value| define_setting key.to_sym, value end end
[ "def", "add", "(", "config", "=", "{", "}", ")", "config", ".", "each", "do", "|", "key", ",", "value", "|", "define_setting", "key", ".", "to_sym", ",", "value", "end", "end" ]
=> Facilitate Dynamic Addition of Configuration Values => @return [class_variable]
[ "=", ">", "Facilitate", "Dynamic", "Addition", "of", "Configuration", "Values" ]
5c67fa2a2f4cd01716a0859dd4b900e740dfc8f7
https://github.com/bdwyertech/chef-rundeck2/blob/5c67fa2a2f4cd01716a0859dd4b900e740dfc8f7/lib/chef-rundeck/config.rb#L71-L75
2,580
bdwyertech/chef-rundeck2
lib/chef-rundeck/chef.rb
ChefRunDeck.Chef.delete
def delete(node) # => Make sure the Node Exists return 'Node not found on Chef Server' unless Node.exists?(node) # => Initialize the Admin API Client Settings admin_api_client # => Delete the Client & Node Object Client.delete(node) Node.delete(node) 'Client/Node Deleted from Chef Server' end
ruby
def delete(node) # => Make sure the Node Exists return 'Node not found on Chef Server' unless Node.exists?(node) # => Initialize the Admin API Client Settings admin_api_client # => Delete the Client & Node Object Client.delete(node) Node.delete(node) 'Client/Node Deleted from Chef Server' end
[ "def", "delete", "(", "node", ")", "# => Make sure the Node Exists", "return", "'Node not found on Chef Server'", "unless", "Node", ".", "exists?", "(", "node", ")", "# => Initialize the Admin API Client Settings", "admin_api_client", "# => Delete the Client & Node Object", "Client", ".", "delete", "(", "node", ")", "Node", ".", "delete", "(", "node", ")", "'Client/Node Deleted from Chef Server'", "end" ]
=> Delete a Node Object
[ "=", ">", "Delete", "a", "Node", "Object" ]
5c67fa2a2f4cd01716a0859dd4b900e740dfc8f7
https://github.com/bdwyertech/chef-rundeck2/blob/5c67fa2a2f4cd01716a0859dd4b900e740dfc8f7/lib/chef-rundeck/chef.rb#L66-L77
2,581
github/octofacts
lib/octofacts_updater/cli.rb
OctofactsUpdater.CLI.run
def run unless opts[:action] usage exit 255 end @config = {} if opts[:config] @config = YAML.load_file(opts[:config]) substitute_relative_paths!(@config, File.dirname(opts[:config])) load_plugins(@config["plugins"]) if @config.key?("plugins") end @config[:options] = {} opts.each do |k, v| if v.is_a?(Hash) @config[k.to_s] ||= {} v.each do |v_key, v_val| @config[k.to_s][v_key.to_s] = v_val @config[k.to_s].delete(v_key.to_s) if v_val.nil? end else @config[:options][k] = v end end return handle_action_bulk if opts[:action] == "bulk" return handle_action_facts if opts[:action] == "facts" return handle_action_bulk if opts[:action] == "reindex" usage exit 255 end
ruby
def run unless opts[:action] usage exit 255 end @config = {} if opts[:config] @config = YAML.load_file(opts[:config]) substitute_relative_paths!(@config, File.dirname(opts[:config])) load_plugins(@config["plugins"]) if @config.key?("plugins") end @config[:options] = {} opts.each do |k, v| if v.is_a?(Hash) @config[k.to_s] ||= {} v.each do |v_key, v_val| @config[k.to_s][v_key.to_s] = v_val @config[k.to_s].delete(v_key.to_s) if v_val.nil? end else @config[:options][k] = v end end return handle_action_bulk if opts[:action] == "bulk" return handle_action_facts if opts[:action] == "facts" return handle_action_bulk if opts[:action] == "reindex" usage exit 255 end
[ "def", "run", "unless", "opts", "[", ":action", "]", "usage", "exit", "255", "end", "@config", "=", "{", "}", "if", "opts", "[", ":config", "]", "@config", "=", "YAML", ".", "load_file", "(", "opts", "[", ":config", "]", ")", "substitute_relative_paths!", "(", "@config", ",", "File", ".", "dirname", "(", "opts", "[", ":config", "]", ")", ")", "load_plugins", "(", "@config", "[", "\"plugins\"", "]", ")", "if", "@config", ".", "key?", "(", "\"plugins\"", ")", "end", "@config", "[", ":options", "]", "=", "{", "}", "opts", ".", "each", "do", "|", "k", ",", "v", "|", "if", "v", ".", "is_a?", "(", "Hash", ")", "@config", "[", "k", ".", "to_s", "]", "||=", "{", "}", "v", ".", "each", "do", "|", "v_key", ",", "v_val", "|", "@config", "[", "k", ".", "to_s", "]", "[", "v_key", ".", "to_s", "]", "=", "v_val", "@config", "[", "k", ".", "to_s", "]", ".", "delete", "(", "v_key", ".", "to_s", ")", "if", "v_val", ".", "nil?", "end", "else", "@config", "[", ":options", "]", "[", "k", "]", "=", "v", "end", "end", "return", "handle_action_bulk", "if", "opts", "[", ":action", "]", "==", "\"bulk\"", "return", "handle_action_facts", "if", "opts", "[", ":action", "]", "==", "\"facts\"", "return", "handle_action_bulk", "if", "opts", "[", ":action", "]", "==", "\"reindex\"", "usage", "exit", "255", "end" ]
Run method. Call this to run the octofacts updater with the object that was previously construcuted.
[ "Run", "method", ".", "Call", "this", "to", "run", "the", "octofacts", "updater", "with", "the", "object", "that", "was", "previously", "construcuted", "." ]
0fe4f4bc1de16f41f6ef2eb45eb1d2d687617ce7
https://github.com/github/octofacts/blob/0fe4f4bc1de16f41f6ef2eb45eb1d2d687617ce7/lib/octofacts_updater/cli.rb#L81-L114
2,582
github/octofacts
lib/octofacts_updater/cli.rb
OctofactsUpdater.CLI.index_file
def index_file @index_file ||= begin if config.fetch("index", {})["file"] return config["index"]["file"] if File.file?(config["index"]["file"]) raise Errno::ENOENT, "Index file (#{config['index']['file'].inspect}) does not exist" end raise ArgumentError, "No index file specified on command line (--index-file) or in configuration file" end end
ruby
def index_file @index_file ||= begin if config.fetch("index", {})["file"] return config["index"]["file"] if File.file?(config["index"]["file"]) raise Errno::ENOENT, "Index file (#{config['index']['file'].inspect}) does not exist" end raise ArgumentError, "No index file specified on command line (--index-file) or in configuration file" end end
[ "def", "index_file", "@index_file", "||=", "begin", "if", "config", ".", "fetch", "(", "\"index\"", ",", "{", "}", ")", "[", "\"file\"", "]", "return", "config", "[", "\"index\"", "]", "[", "\"file\"", "]", "if", "File", ".", "file?", "(", "config", "[", "\"index\"", "]", "[", "\"file\"", "]", ")", "raise", "Errno", "::", "ENOENT", ",", "\"Index file (#{config['index']['file'].inspect}) does not exist\"", "end", "raise", "ArgumentError", ",", "\"No index file specified on command line (--index-file) or in configuration file\"", "end", "end" ]
Get the index file from the options or configuration file. Raise error if it does not exist or was not specified.
[ "Get", "the", "index", "file", "from", "the", "options", "or", "configuration", "file", ".", "Raise", "error", "if", "it", "does", "not", "exist", "or", "was", "not", "specified", "." ]
0fe4f4bc1de16f41f6ef2eb45eb1d2d687617ce7
https://github.com/github/octofacts/blob/0fe4f4bc1de16f41f6ef2eb45eb1d2d687617ce7/lib/octofacts_updater/cli.rb#L214-L222
2,583
github/octofacts
lib/octofacts_updater/cli.rb
OctofactsUpdater.CLI.print_or_write
def print_or_write(data) if opts[:output_file] File.open(opts[:output_file], "w") { |f| f.write(data) } else puts data end end
ruby
def print_or_write(data) if opts[:output_file] File.open(opts[:output_file], "w") { |f| f.write(data) } else puts data end end
[ "def", "print_or_write", "(", "data", ")", "if", "opts", "[", ":output_file", "]", "File", ".", "open", "(", "opts", "[", ":output_file", "]", ",", "\"w\"", ")", "{", "|", "f", "|", "f", ".", "write", "(", "data", ")", "}", "else", "puts", "data", "end", "end" ]
Print or write to file depending on whether or not the output file was set. data - Data to print or write.
[ "Print", "or", "write", "to", "file", "depending", "on", "whether", "or", "not", "the", "output", "file", "was", "set", "." ]
0fe4f4bc1de16f41f6ef2eb45eb1d2d687617ce7
https://github.com/github/octofacts/blob/0fe4f4bc1de16f41f6ef2eb45eb1d2d687617ce7/lib/octofacts_updater/cli.rb#L245-L251
2,584
joeyates/rake-builder
lib/rake/builder.rb
Rake.Builder.ensure_headers
def ensure_headers missing = missing_headers return if missing.size == 0 message = "Compilation cannot proceed as the following header files are missing:\n" + missing.join("\n") raise Error.new(message) end
ruby
def ensure_headers missing = missing_headers return if missing.size == 0 message = "Compilation cannot proceed as the following header files are missing:\n" + missing.join("\n") raise Error.new(message) end
[ "def", "ensure_headers", "missing", "=", "missing_headers", "return", "if", "missing", ".", "size", "==", "0", "message", "=", "\"Compilation cannot proceed as the following header files are missing:\\n\"", "+", "missing", ".", "join", "(", "\"\\n\"", ")", "raise", "Error", ".", "new", "(", "message", ")", "end" ]
Raises an error if there are missing headers
[ "Raises", "an", "error", "if", "there", "are", "missing", "headers" ]
38e840fc8575fb7c05b631afa1cddab7914234ea
https://github.com/joeyates/rake-builder/blob/38e840fc8575fb7c05b631afa1cddab7914234ea/lib/rake/builder.rb#L301-L307
2,585
joeyates/rake-builder
lib/rake/builder.rb
Rake.Builder.source_files
def source_files return @source_files if @source_files old_dir = Dir.pwd Dir.chdir @rakefile_path @source_files = Rake::Path.find_files(@source_search_paths, source_file_extension).uniq.sort Dir.chdir old_dir @source_files end
ruby
def source_files return @source_files if @source_files old_dir = Dir.pwd Dir.chdir @rakefile_path @source_files = Rake::Path.find_files(@source_search_paths, source_file_extension).uniq.sort Dir.chdir old_dir @source_files end
[ "def", "source_files", "return", "@source_files", "if", "@source_files", "old_dir", "=", "Dir", ".", "pwd", "Dir", ".", "chdir", "@rakefile_path", "@source_files", "=", "Rake", "::", "Path", ".", "find_files", "(", "@source_search_paths", ",", "source_file_extension", ")", ".", "uniq", ".", "sort", "Dir", ".", "chdir", "old_dir", "@source_files", "end" ]
Source files found in source_search_paths
[ "Source", "files", "found", "in", "source_search_paths" ]
38e840fc8575fb7c05b631afa1cddab7914234ea
https://github.com/joeyates/rake-builder/blob/38e840fc8575fb7c05b631afa1cddab7914234ea/lib/rake/builder.rb#L351-L359
2,586
Aerlinger/attr_deprecated
lib/attr_deprecated.rb
AttrDeprecated.ClassMethods._set_attribute_as_deprecated
def _set_attribute_as_deprecated(attribute) original_attribute_method = instance_method(attribute.to_sym) klass = self define_method attribute.to_sym do |*args| backtrace_cleaner = ActiveSupport::BacktraceCleaner.new backtrace = backtrace_cleaner.clean(caller) klass._notify_deprecated_attribute_call({klass: self, attribute: attribute, args: args, backtrace: backtrace}) # Call the original attribute method. original_attribute_method.bind(self).call(*args) end end
ruby
def _set_attribute_as_deprecated(attribute) original_attribute_method = instance_method(attribute.to_sym) klass = self define_method attribute.to_sym do |*args| backtrace_cleaner = ActiveSupport::BacktraceCleaner.new backtrace = backtrace_cleaner.clean(caller) klass._notify_deprecated_attribute_call({klass: self, attribute: attribute, args: args, backtrace: backtrace}) # Call the original attribute method. original_attribute_method.bind(self).call(*args) end end
[ "def", "_set_attribute_as_deprecated", "(", "attribute", ")", "original_attribute_method", "=", "instance_method", "(", "attribute", ".", "to_sym", ")", "klass", "=", "self", "define_method", "attribute", ".", "to_sym", "do", "|", "*", "args", "|", "backtrace_cleaner", "=", "ActiveSupport", "::", "BacktraceCleaner", ".", "new", "backtrace", "=", "backtrace_cleaner", ".", "clean", "(", "caller", ")", "klass", ".", "_notify_deprecated_attribute_call", "(", "{", "klass", ":", "self", ",", "attribute", ":", "attribute", ",", "args", ":", "args", ",", "backtrace", ":", "backtrace", "}", ")", "# Call the original attribute method.", "original_attribute_method", ".", "bind", "(", "self", ")", ".", "call", "(", "args", ")", "end", "end" ]
Wrap the original attribute method with appropriate notification while leaving the functionality of the original method unchanged.
[ "Wrap", "the", "original", "attribute", "method", "with", "appropriate", "notification", "while", "leaving", "the", "functionality", "of", "the", "original", "method", "unchanged", "." ]
ead9483a7e220ffd987d8f06f0c0ccabc713500e
https://github.com/Aerlinger/attr_deprecated/blob/ead9483a7e220ffd987d8f06f0c0ccabc713500e/lib/attr_deprecated.rb#L77-L91
2,587
github/octofacts
lib/octofacts_updater/fact_index.rb
OctofactsUpdater.FactIndex.reindex
def reindex(facts_to_index, fixtures) @index_data = {} facts_to_index.each { |fact| add(fact, fixtures) } set_top_level_nodes_fact(fixtures) end
ruby
def reindex(facts_to_index, fixtures) @index_data = {} facts_to_index.each { |fact| add(fact, fixtures) } set_top_level_nodes_fact(fixtures) end
[ "def", "reindex", "(", "facts_to_index", ",", "fixtures", ")", "@index_data", "=", "{", "}", "facts_to_index", ".", "each", "{", "|", "fact", "|", "add", "(", "fact", ",", "fixtures", ")", "}", "set_top_level_nodes_fact", "(", "fixtures", ")", "end" ]
Rebuild an index with a specified list of facts. This will remove any indexed facts that are not on the list of facts to use. facts_to_index - An Array of Strings with facts to index fixtures - An Array with fact fixtures (must respond to .facts and .hostname)
[ "Rebuild", "an", "index", "with", "a", "specified", "list", "of", "facts", ".", "This", "will", "remove", "any", "indexed", "facts", "that", "are", "not", "on", "the", "list", "of", "facts", "to", "use", "." ]
0fe4f4bc1de16f41f6ef2eb45eb1d2d687617ce7
https://github.com/github/octofacts/blob/0fe4f4bc1de16f41f6ef2eb45eb1d2d687617ce7/lib/octofacts_updater/fact_index.rb#L92-L96
2,588
github/octofacts
lib/octofacts_updater/fact_index.rb
OctofactsUpdater.FactIndex.write_file
def write_file(filename = nil) filename ||= @filename unless filename.is_a?(String) raise ArgumentError, "Called write_file() for fact_index without a filename" end File.open(filename, "w") { |f| f.write(to_yaml) } end
ruby
def write_file(filename = nil) filename ||= @filename unless filename.is_a?(String) raise ArgumentError, "Called write_file() for fact_index without a filename" end File.open(filename, "w") { |f| f.write(to_yaml) } end
[ "def", "write_file", "(", "filename", "=", "nil", ")", "filename", "||=", "@filename", "unless", "filename", ".", "is_a?", "(", "String", ")", "raise", "ArgumentError", ",", "\"Called write_file() for fact_index without a filename\"", "end", "File", ".", "open", "(", "filename", ",", "\"w\"", ")", "{", "|", "f", "|", "f", ".", "write", "(", "to_yaml", ")", "}", "end" ]
Write the fact index out to a YAML file. filename - A String with the file to write (defaults to filename from constructor if available)
[ "Write", "the", "fact", "index", "out", "to", "a", "YAML", "file", "." ]
0fe4f4bc1de16f41f6ef2eb45eb1d2d687617ce7
https://github.com/github/octofacts/blob/0fe4f4bc1de16f41f6ef2eb45eb1d2d687617ce7/lib/octofacts_updater/fact_index.rb#L126-L132
2,589
Tapjoy/chore
lib/chore/job.rb
Chore.Job.perform_async
def perform_async(*args) self.class.run_hooks_for(:before_publish,*args) @chore_publisher ||= self.class.options[:publisher] @chore_publisher.publish(self.class.prefixed_queue_name,self.class.job_hash(args)) self.class.run_hooks_for(:after_publish,*args) end
ruby
def perform_async(*args) self.class.run_hooks_for(:before_publish,*args) @chore_publisher ||= self.class.options[:publisher] @chore_publisher.publish(self.class.prefixed_queue_name,self.class.job_hash(args)) self.class.run_hooks_for(:after_publish,*args) end
[ "def", "perform_async", "(", "*", "args", ")", "self", ".", "class", ".", "run_hooks_for", "(", ":before_publish", ",", "args", ")", "@chore_publisher", "||=", "self", ".", "class", ".", "options", "[", ":publisher", "]", "@chore_publisher", ".", "publish", "(", "self", ".", "class", ".", "prefixed_queue_name", ",", "self", ".", "class", ".", "job_hash", "(", "args", ")", ")", "self", ".", "class", ".", "run_hooks_for", "(", ":after_publish", ",", "args", ")", "end" ]
Use the current configured publisher to send this job into a queue.
[ "Use", "the", "current", "configured", "publisher", "to", "send", "this", "job", "into", "a", "queue", "." ]
f3d978cb6e5f20aa2a163f2c80f3c1c2efa93ef1
https://github.com/Tapjoy/chore/blob/f3d978cb6e5f20aa2a163f2c80f3c1c2efa93ef1/lib/chore/job.rb#L125-L130
2,590
unboxed/be_valid_asset
lib/be_valid_asset/be_valid_feed.rb
BeValidAsset.BeValidFeed.response_indicates_valid?
def response_indicates_valid?(response) REXML::Document.new(response.body).root.get_elements('//m:validity').first.text == 'true' end
ruby
def response_indicates_valid?(response) REXML::Document.new(response.body).root.get_elements('//m:validity').first.text == 'true' end
[ "def", "response_indicates_valid?", "(", "response", ")", "REXML", "::", "Document", ".", "new", "(", "response", ".", "body", ")", ".", "root", ".", "get_elements", "(", "'//m:validity'", ")", ".", "first", ".", "text", "==", "'true'", "end" ]
The feed validator uses a different response type, so we have to override these here.
[ "The", "feed", "validator", "uses", "a", "different", "response", "type", "so", "we", "have", "to", "override", "these", "here", "." ]
a4d2096d2b6f108c9fb06e0431bc854479a9cd1f
https://github.com/unboxed/be_valid_asset/blob/a4d2096d2b6f108c9fb06e0431bc854479a9cd1f/lib/be_valid_asset/be_valid_feed.rb#L47-L49
2,591
github/octofacts
lib/octofacts/facts.rb
Octofacts.Facts.method_missing
def method_missing(name, *args, &block) if Octofacts::Manipulators.run(self, name, *args, &block) @facts_manipulated = true return self end if facts.respond_to?(name, false) if args[0].is_a?(String) || args[0].is_a?(Symbol) args[0] = string_or_symbolized_key(args[0]) end return facts.send(name, *args) end raise NameError, "Unknown method '#{name}' in #{self.class}" end
ruby
def method_missing(name, *args, &block) if Octofacts::Manipulators.run(self, name, *args, &block) @facts_manipulated = true return self end if facts.respond_to?(name, false) if args[0].is_a?(String) || args[0].is_a?(Symbol) args[0] = string_or_symbolized_key(args[0]) end return facts.send(name, *args) end raise NameError, "Unknown method '#{name}' in #{self.class}" end
[ "def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "block", ")", "if", "Octofacts", "::", "Manipulators", ".", "run", "(", "self", ",", "name", ",", "args", ",", "block", ")", "@facts_manipulated", "=", "true", "return", "self", "end", "if", "facts", ".", "respond_to?", "(", "name", ",", "false", ")", "if", "args", "[", "0", "]", ".", "is_a?", "(", "String", ")", "||", "args", "[", "0", "]", ".", "is_a?", "(", "Symbol", ")", "args", "[", "0", "]", "=", "string_or_symbolized_key", "(", "args", "[", "0", "]", ")", "end", "return", "facts", ".", "send", "(", "name", ",", "args", ")", "end", "raise", "NameError", ",", "\"Unknown method '#{name}' in #{self.class}\"", "end" ]
Missing method - this is used to dispatch to manipulators or to call a Hash method in the facts. Try calling a Manipulator method, delegate to the facts hash or else error out. Returns this object (so that calls to manipulators can be chained).
[ "Missing", "method", "-", "this", "is", "used", "to", "dispatch", "to", "manipulators", "or", "to", "call", "a", "Hash", "method", "in", "the", "facts", "." ]
0fe4f4bc1de16f41f6ef2eb45eb1d2d687617ce7
https://github.com/github/octofacts/blob/0fe4f4bc1de16f41f6ef2eb45eb1d2d687617ce7/lib/octofacts/facts.rb#L78-L92
2,592
bdwyertech/chef-rundeck2
lib/chef-rundeck/cli.rb
ChefRunDeck.CLI.run
def run(argv = ARGV) # => Parse CLI Configuration cli = Options.new cli.parse_options(argv) # => Grab the Default Values default = Config.options # => Parse JSON Config File (If Specified and Exists) json_config = Util.parse_json_config(cli.config[:config_file] || Config.config_file) # => Merge Configuration (CLI Wins) config = [default, json_config, cli.config].compact.reduce(:merge) # => Apply Configuration Config.setup do |cfg| cfg.config_file = config[:config_file] cfg.cache_timeout = config[:cache_timeout].to_i cfg.bind = config[:bind] cfg.port = config[:port] cfg.auth_file = config[:auth_file] cfg.state_file = config[:state_file] cfg.environment = config[:environment].to_sym.downcase cfg.chef_api_endpoint = config[:chef_api_endpoint] cfg.chef_api_client = config[:chef_api_client] cfg.chef_api_client_key = config[:chef_api_client_key] cfg.chef_api_admin = config[:chef_api_admin] cfg.chef_api_admin_key = config[:chef_api_admin_key] cfg.rd_node_username = config[:rd_node_username] end # => Launch the API API.run! end
ruby
def run(argv = ARGV) # => Parse CLI Configuration cli = Options.new cli.parse_options(argv) # => Grab the Default Values default = Config.options # => Parse JSON Config File (If Specified and Exists) json_config = Util.parse_json_config(cli.config[:config_file] || Config.config_file) # => Merge Configuration (CLI Wins) config = [default, json_config, cli.config].compact.reduce(:merge) # => Apply Configuration Config.setup do |cfg| cfg.config_file = config[:config_file] cfg.cache_timeout = config[:cache_timeout].to_i cfg.bind = config[:bind] cfg.port = config[:port] cfg.auth_file = config[:auth_file] cfg.state_file = config[:state_file] cfg.environment = config[:environment].to_sym.downcase cfg.chef_api_endpoint = config[:chef_api_endpoint] cfg.chef_api_client = config[:chef_api_client] cfg.chef_api_client_key = config[:chef_api_client_key] cfg.chef_api_admin = config[:chef_api_admin] cfg.chef_api_admin_key = config[:chef_api_admin_key] cfg.rd_node_username = config[:rd_node_username] end # => Launch the API API.run! end
[ "def", "run", "(", "argv", "=", "ARGV", ")", "# => Parse CLI Configuration", "cli", "=", "Options", ".", "new", "cli", ".", "parse_options", "(", "argv", ")", "# => Grab the Default Values", "default", "=", "Config", ".", "options", "# => Parse JSON Config File (If Specified and Exists)", "json_config", "=", "Util", ".", "parse_json_config", "(", "cli", ".", "config", "[", ":config_file", "]", "||", "Config", ".", "config_file", ")", "# => Merge Configuration (CLI Wins)", "config", "=", "[", "default", ",", "json_config", ",", "cli", ".", "config", "]", ".", "compact", ".", "reduce", "(", ":merge", ")", "# => Apply Configuration", "Config", ".", "setup", "do", "|", "cfg", "|", "cfg", ".", "config_file", "=", "config", "[", ":config_file", "]", "cfg", ".", "cache_timeout", "=", "config", "[", ":cache_timeout", "]", ".", "to_i", "cfg", ".", "bind", "=", "config", "[", ":bind", "]", "cfg", ".", "port", "=", "config", "[", ":port", "]", "cfg", ".", "auth_file", "=", "config", "[", ":auth_file", "]", "cfg", ".", "state_file", "=", "config", "[", ":state_file", "]", "cfg", ".", "environment", "=", "config", "[", ":environment", "]", ".", "to_sym", ".", "downcase", "cfg", ".", "chef_api_endpoint", "=", "config", "[", ":chef_api_endpoint", "]", "cfg", ".", "chef_api_client", "=", "config", "[", ":chef_api_client", "]", "cfg", ".", "chef_api_client_key", "=", "config", "[", ":chef_api_client_key", "]", "cfg", ".", "chef_api_admin", "=", "config", "[", ":chef_api_admin", "]", "cfg", ".", "chef_api_admin_key", "=", "config", "[", ":chef_api_admin_key", "]", "cfg", ".", "rd_node_username", "=", "config", "[", ":rd_node_username", "]", "end", "# => Launch the API", "API", ".", "run!", "end" ]
=> Launch the Application
[ "=", ">", "Launch", "the", "Application" ]
5c67fa2a2f4cd01716a0859dd4b900e740dfc8f7
https://github.com/bdwyertech/chef-rundeck2/blob/5c67fa2a2f4cd01716a0859dd4b900e740dfc8f7/lib/chef-rundeck/cli.rb#L97-L130
2,593
soracom/soracom-sdk-ruby
lib/soracom/client.rb
Soracom.Client.auth_by_user
def auth_by_user(operator_id, user_name, password, endpoint) endpoint = API_BASE_URL if endpoint.nil? res = RestClient.post endpoint + '/auth', { operatorId: operator_id, userName: user_name, password: password }, 'Content-Type' => 'application/json', 'Accept' => 'application/json' result = JSON.parse(res.body) fail result['message'] if res.code != '200' Hash[JSON.parse(res.body).map { |k, v| [k.to_sym, v] }] end
ruby
def auth_by_user(operator_id, user_name, password, endpoint) endpoint = API_BASE_URL if endpoint.nil? res = RestClient.post endpoint + '/auth', { operatorId: operator_id, userName: user_name, password: password }, 'Content-Type' => 'application/json', 'Accept' => 'application/json' result = JSON.parse(res.body) fail result['message'] if res.code != '200' Hash[JSON.parse(res.body).map { |k, v| [k.to_sym, v] }] end
[ "def", "auth_by_user", "(", "operator_id", ",", "user_name", ",", "password", ",", "endpoint", ")", "endpoint", "=", "API_BASE_URL", "if", "endpoint", ".", "nil?", "res", "=", "RestClient", ".", "post", "endpoint", "+", "'/auth'", ",", "{", "operatorId", ":", "operator_id", ",", "userName", ":", "user_name", ",", "password", ":", "password", "}", ",", "'Content-Type'", "=>", "'application/json'", ",", "'Accept'", "=>", "'application/json'", "result", "=", "JSON", ".", "parse", "(", "res", ".", "body", ")", "fail", "result", "[", "'message'", "]", "if", "res", ".", "code", "!=", "'200'", "Hash", "[", "JSON", ".", "parse", "(", "res", ".", "body", ")", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ".", "to_sym", ",", "v", "]", "}", "]", "end" ]
authenticate by operator_id and user_name and password
[ "authenticate", "by", "operator_id", "and", "user_name", "and", "password" ]
7e8e2158a7818ffc62191fb15b948f633b1d49d1
https://github.com/soracom/soracom-sdk-ruby/blob/7e8e2158a7818ffc62191fb15b948f633b1d49d1/lib/soracom/client.rb#L538-L547
2,594
github/octofacts
lib/octofacts_updater/fact.rb
OctofactsUpdater.Fact.set_value
def set_value(new_value, name_in = nil) if name_in.nil? if new_value.is_a?(Proc) return @value = new_value.call(@value) end return @value = new_value end parts = if name_in.is_a?(String) name_in.split("::") elsif name_in.is_a?(Array) name_in.map do |item| if item.is_a?(String) item elsif item.is_a?(Hash) && item.key?("regexp") Regexp.new(item["regexp"]) else raise ArgumentError, "Unable to interpret structure item: #{item.inspect}" end end else raise ArgumentError, "Unable to interpret structure: #{name_in.inspect}" end set_structured_value(@value, parts, new_value) end
ruby
def set_value(new_value, name_in = nil) if name_in.nil? if new_value.is_a?(Proc) return @value = new_value.call(@value) end return @value = new_value end parts = if name_in.is_a?(String) name_in.split("::") elsif name_in.is_a?(Array) name_in.map do |item| if item.is_a?(String) item elsif item.is_a?(Hash) && item.key?("regexp") Regexp.new(item["regexp"]) else raise ArgumentError, "Unable to interpret structure item: #{item.inspect}" end end else raise ArgumentError, "Unable to interpret structure: #{name_in.inspect}" end set_structured_value(@value, parts, new_value) end
[ "def", "set_value", "(", "new_value", ",", "name_in", "=", "nil", ")", "if", "name_in", ".", "nil?", "if", "new_value", ".", "is_a?", "(", "Proc", ")", "return", "@value", "=", "new_value", ".", "call", "(", "@value", ")", "end", "return", "@value", "=", "new_value", "end", "parts", "=", "if", "name_in", ".", "is_a?", "(", "String", ")", "name_in", ".", "split", "(", "\"::\"", ")", "elsif", "name_in", ".", "is_a?", "(", "Array", ")", "name_in", ".", "map", "do", "|", "item", "|", "if", "item", ".", "is_a?", "(", "String", ")", "item", "elsif", "item", ".", "is_a?", "(", "Hash", ")", "&&", "item", ".", "key?", "(", "\"regexp\"", ")", "Regexp", ".", "new", "(", "item", "[", "\"regexp\"", "]", ")", "else", "raise", "ArgumentError", ",", "\"Unable to interpret structure item: #{item.inspect}\"", "end", "end", "else", "raise", "ArgumentError", ",", "\"Unable to interpret structure: #{name_in.inspect}\"", "end", "set_structured_value", "(", "@value", ",", "parts", ",", "new_value", ")", "end" ]
Set the value of the fact. If the name is specified, this will dig into a structured fact to set the value within the structure. new_value - An object with the new value for the fact name_in - An optional String to dig into the structure (formatted with :: indicating hash delimiters)
[ "Set", "the", "value", "of", "the", "fact", ".", "If", "the", "name", "is", "specified", "this", "will", "dig", "into", "a", "structured", "fact", "to", "set", "the", "value", "within", "the", "structure", "." ]
0fe4f4bc1de16f41f6ef2eb45eb1d2d687617ce7
https://github.com/github/octofacts/blob/0fe4f4bc1de16f41f6ef2eb45eb1d2d687617ce7/lib/octofacts_updater/fact.rb#L58-L84
2,595
github/octofacts
lib/octofacts_updater/fact.rb
OctofactsUpdater.Fact.set_structured_value
def set_structured_value(subhash, parts, value) return if subhash.nil? raise ArgumentError, "Cannot set structured value at #{parts.first.inspect}" unless subhash.is_a?(Hash) raise ArgumentError, "parts must be an Array, got #{parts.inspect}" unless parts.is_a?(Array) # At the top level, find all keys that match the first item in the parts. matching_keys = subhash.keys.select do |key| if parts.first.is_a?(String) key == parts.first elsif parts.first.is_a?(Regexp) parts.first.match(key) else # :nocov: # This is a bug - this code should be unreachable because of the checking in `set_value` raise ArgumentError, "part must be a string or regexp, got #{parts.first.inspect}" # :nocov: end end # Auto-create a new hash if there is a value, the part is a string, and the key doesn't exist. if parts.first.is_a?(String) && !value.nil? && !subhash.key?(parts.first) subhash[parts.first] = {} matching_keys << parts.first end return unless matching_keys.any? # If we are at the end, set the value or delete the key. if parts.size == 1 if value.nil? matching_keys.each { |k| subhash.delete(k) } elsif value.is_a?(Proc) matching_keys.each do |k| new_value = value.call(subhash[k]) if new_value.nil? subhash.delete(k) else subhash[k] = new_value end end else matching_keys.each { |k| subhash[k] = value } end return end # We are not at the end. Recurse down to the next level. matching_keys.each { |k| set_structured_value(subhash[k], parts[1..-1], value) } end
ruby
def set_structured_value(subhash, parts, value) return if subhash.nil? raise ArgumentError, "Cannot set structured value at #{parts.first.inspect}" unless subhash.is_a?(Hash) raise ArgumentError, "parts must be an Array, got #{parts.inspect}" unless parts.is_a?(Array) # At the top level, find all keys that match the first item in the parts. matching_keys = subhash.keys.select do |key| if parts.first.is_a?(String) key == parts.first elsif parts.first.is_a?(Regexp) parts.first.match(key) else # :nocov: # This is a bug - this code should be unreachable because of the checking in `set_value` raise ArgumentError, "part must be a string or regexp, got #{parts.first.inspect}" # :nocov: end end # Auto-create a new hash if there is a value, the part is a string, and the key doesn't exist. if parts.first.is_a?(String) && !value.nil? && !subhash.key?(parts.first) subhash[parts.first] = {} matching_keys << parts.first end return unless matching_keys.any? # If we are at the end, set the value or delete the key. if parts.size == 1 if value.nil? matching_keys.each { |k| subhash.delete(k) } elsif value.is_a?(Proc) matching_keys.each do |k| new_value = value.call(subhash[k]) if new_value.nil? subhash.delete(k) else subhash[k] = new_value end end else matching_keys.each { |k| subhash[k] = value } end return end # We are not at the end. Recurse down to the next level. matching_keys.each { |k| set_structured_value(subhash[k], parts[1..-1], value) } end
[ "def", "set_structured_value", "(", "subhash", ",", "parts", ",", "value", ")", "return", "if", "subhash", ".", "nil?", "raise", "ArgumentError", ",", "\"Cannot set structured value at #{parts.first.inspect}\"", "unless", "subhash", ".", "is_a?", "(", "Hash", ")", "raise", "ArgumentError", ",", "\"parts must be an Array, got #{parts.inspect}\"", "unless", "parts", ".", "is_a?", "(", "Array", ")", "# At the top level, find all keys that match the first item in the parts.", "matching_keys", "=", "subhash", ".", "keys", ".", "select", "do", "|", "key", "|", "if", "parts", ".", "first", ".", "is_a?", "(", "String", ")", "key", "==", "parts", ".", "first", "elsif", "parts", ".", "first", ".", "is_a?", "(", "Regexp", ")", "parts", ".", "first", ".", "match", "(", "key", ")", "else", "# :nocov:", "# This is a bug - this code should be unreachable because of the checking in `set_value`", "raise", "ArgumentError", ",", "\"part must be a string or regexp, got #{parts.first.inspect}\"", "# :nocov:", "end", "end", "# Auto-create a new hash if there is a value, the part is a string, and the key doesn't exist.", "if", "parts", ".", "first", ".", "is_a?", "(", "String", ")", "&&", "!", "value", ".", "nil?", "&&", "!", "subhash", ".", "key?", "(", "parts", ".", "first", ")", "subhash", "[", "parts", ".", "first", "]", "=", "{", "}", "matching_keys", "<<", "parts", ".", "first", "end", "return", "unless", "matching_keys", ".", "any?", "# If we are at the end, set the value or delete the key.", "if", "parts", ".", "size", "==", "1", "if", "value", ".", "nil?", "matching_keys", ".", "each", "{", "|", "k", "|", "subhash", ".", "delete", "(", "k", ")", "}", "elsif", "value", ".", "is_a?", "(", "Proc", ")", "matching_keys", ".", "each", "do", "|", "k", "|", "new_value", "=", "value", ".", "call", "(", "subhash", "[", "k", "]", ")", "if", "new_value", ".", "nil?", "subhash", ".", "delete", "(", "k", ")", "else", "subhash", "[", "k", "]", "=", "new_value", "end", "end", "else", "matching_keys", ".", "each", "{", "|", "k", "|", "subhash", "[", "k", "]", "=", "value", "}", "end", "return", "end", "# We are not at the end. Recurse down to the next level.", "matching_keys", ".", "each", "{", "|", "k", "|", "set_structured_value", "(", "subhash", "[", "k", "]", ",", "parts", "[", "1", "..", "-", "1", "]", ",", "value", ")", "}", "end" ]
Set a value in the data structure of a structured fact. This is intended to be called recursively. subhash - The Hash, part of the fact, being operated upon parts - The Array to dig in to the hash value - The value to set the ultimate last part to Does not return anything, but modifies 'subhash'
[ "Set", "a", "value", "in", "the", "data", "structure", "of", "a", "structured", "fact", ".", "This", "is", "intended", "to", "be", "called", "recursively", "." ]
0fe4f4bc1de16f41f6ef2eb45eb1d2d687617ce7
https://github.com/github/octofacts/blob/0fe4f4bc1de16f41f6ef2eb45eb1d2d687617ce7/lib/octofacts_updater/fact.rb#L96-L143
2,596
imathis/clash
lib/clash/diff.rb
Clash.Diff.diff_dirs
def diff_dirs(dir1, dir2) mattching_dir_files(dir1, dir2).each do |file| a = File.join(dir1, file) b = File.join(dir2, file) diff_files(a,b) end end
ruby
def diff_dirs(dir1, dir2) mattching_dir_files(dir1, dir2).each do |file| a = File.join(dir1, file) b = File.join(dir2, file) diff_files(a,b) end end
[ "def", "diff_dirs", "(", "dir1", ",", "dir2", ")", "mattching_dir_files", "(", "dir1", ",", "dir2", ")", ".", "each", "do", "|", "file", "|", "a", "=", "File", ".", "join", "(", "dir1", ",", "file", ")", "b", "=", "File", ".", "join", "(", "dir2", ",", "file", ")", "diff_files", "(", "a", ",", "b", ")", "end", "end" ]
Recursively diff common files between dir1 and dir2
[ "Recursively", "diff", "common", "files", "between", "dir1", "and", "dir2" ]
961fe5d7719789afc47486ac2f3b84e9cdcce769
https://github.com/imathis/clash/blob/961fe5d7719789afc47486ac2f3b84e9cdcce769/lib/clash/diff.rb#L39-L45
2,597
imathis/clash
lib/clash/diff.rb
Clash.Diff.dir_files
def dir_files(dir) Find.find(dir).to_a.reject!{|f| File.directory?(f) } end
ruby
def dir_files(dir) Find.find(dir).to_a.reject!{|f| File.directory?(f) } end
[ "def", "dir_files", "(", "dir", ")", "Find", ".", "find", "(", "dir", ")", ".", "to_a", ".", "reject!", "{", "|", "f", "|", "File", ".", "directory?", "(", "f", ")", "}", "end" ]
Find all files in a given directory
[ "Find", "all", "files", "in", "a", "given", "directory" ]
961fe5d7719789afc47486ac2f3b84e9cdcce769
https://github.com/imathis/clash/blob/961fe5d7719789afc47486ac2f3b84e9cdcce769/lib/clash/diff.rb#L63-L65
2,598
imathis/clash
lib/clash/diff.rb
Clash.Diff.unique_files
def unique_files(dir, dir_files, common_files) unique = dir_files - common_files if !unique.empty? @test_failures << yellowit("\nMissing from directory #{dir}:\n") unique.each do |f| failure = " - #{f}" failure << "\n" if unique.last == f @test_failures << failure end end end
ruby
def unique_files(dir, dir_files, common_files) unique = dir_files - common_files if !unique.empty? @test_failures << yellowit("\nMissing from directory #{dir}:\n") unique.each do |f| failure = " - #{f}" failure << "\n" if unique.last == f @test_failures << failure end end end
[ "def", "unique_files", "(", "dir", ",", "dir_files", ",", "common_files", ")", "unique", "=", "dir_files", "-", "common_files", "if", "!", "unique", ".", "empty?", "@test_failures", "<<", "yellowit", "(", "\"\\nMissing from directory #{dir}:\\n\"", ")", "unique", ".", "each", "do", "|", "f", "|", "failure", "=", "\" - #{f}\"", "failure", "<<", "\"\\n\"", "if", "unique", ".", "last", "==", "f", "@test_failures", "<<", "failure", "end", "end", "end" ]
Find files which aren't common to both directories
[ "Find", "files", "which", "aren", "t", "common", "to", "both", "directories" ]
961fe5d7719789afc47486ac2f3b84e9cdcce769
https://github.com/imathis/clash/blob/961fe5d7719789afc47486ac2f3b84e9cdcce769/lib/clash/diff.rb#L69-L79
2,599
github/octofacts
lib/octofacts_updater/fixture.rb
OctofactsUpdater.Fixture.to_yaml
def to_yaml sorted_facts = @facts.sort.to_h facts_hash_with_expanded_values = Hash[sorted_facts.collect { |k, v| [k, v.value] }] YAML.dump(facts_hash_with_expanded_values) end
ruby
def to_yaml sorted_facts = @facts.sort.to_h facts_hash_with_expanded_values = Hash[sorted_facts.collect { |k, v| [k, v.value] }] YAML.dump(facts_hash_with_expanded_values) end
[ "def", "to_yaml", "sorted_facts", "=", "@facts", ".", "sort", ".", "to_h", "facts_hash_with_expanded_values", "=", "Hash", "[", "sorted_facts", ".", "collect", "{", "|", "k", ",", "v", "|", "[", "k", ",", "v", ".", "value", "]", "}", "]", "YAML", ".", "dump", "(", "facts_hash_with_expanded_values", ")", "end" ]
YAML representation of the fact fixture. Returns a String containing the YAML representation of the fact fixture.
[ "YAML", "representation", "of", "the", "fact", "fixture", "." ]
0fe4f4bc1de16f41f6ef2eb45eb1d2d687617ce7
https://github.com/github/octofacts/blob/0fe4f4bc1de16f41f6ef2eb45eb1d2d687617ce7/lib/octofacts_updater/fixture.rb#L130-L134