code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def default_output_price 1.10 # Default to chat output price end
Default output price when model family can't be determined @return [Float] the default output price
default_output_price
ruby
crmne/ruby_llm
lib/ruby_llm/providers/deepseek/capabilities.rb
https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/deepseek/capabilities.rb
MIT
def default_cache_hit_price 0.07 # Default to chat cache hit price end
Default cache hit price when model family can't be determined @return [Float] the default cache hit price
default_cache_hit_price
ruby
crmne/ruby_llm
lib/ruby_llm/providers/deepseek/capabilities.rb
https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/deepseek/capabilities.rb
MIT
def max_tokens_for(model_id) case model_id when /gemini-2\.5-pro-exp-03-25/ then 64_000 when /gemini-2\.0-flash/, /gemini-2\.0-flash-lite/, /gemini-1\.5-flash/, /gemini-1\.5-flash-8b/, /gemini-1\.5-pro/ # rubocop:disable Layout/LineLength 8_192 when /gemini-embedding-exp/ then nil # Elastic, supports 3072, 1536, or 768 when /text-embedding-004/, /embedding-001/ then 768 # Output dimension size for embeddings when /aqa/ then 1_024 when /imagen-3/ then 4 # Output images else 4_096 # Sensible default end end
Returns the maximum output tokens for the given model @param model_id [String] the model identifier @return [Integer] the maximum output tokens
max_tokens_for
ruby
crmne/ruby_llm
lib/ruby_llm/providers/gemini/capabilities.rb
https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/gemini/capabilities.rb
MIT
def input_price_for(model_id) base_price = PRICES.dig(pricing_family(model_id), :input) || default_input_price return base_price unless long_context_model?(model_id) # Apply different pricing for prompts longer than 128k tokens context_window_for(model_id) > 128_000 ? base_price * 2 : base_price end
Returns the input price per million tokens for the given model @param model_id [String] the model identifier @return [Float] the price per million tokens in USD
input_price_for
ruby
crmne/ruby_llm
lib/ruby_llm/providers/gemini/capabilities.rb
https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/gemini/capabilities.rb
MIT
def output_price_for(model_id) base_price = PRICES.dig(pricing_family(model_id), :output) || default_output_price return base_price unless long_context_model?(model_id) # Apply different pricing for prompts longer than 128k tokens context_window_for(model_id) > 128_000 ? base_price * 2 : base_price end
Returns the output price per million tokens for the given model @param model_id [String] the model identifier @return [Float] the price per million tokens in USD
output_price_for
ruby
crmne/ruby_llm
lib/ruby_llm/providers/gemini/capabilities.rb
https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/gemini/capabilities.rb
MIT
def supports_vision?(model_id) return false if model_id.match?(/text-embedding|embedding-001|aqa/) model_id.match?(/gemini|flash|pro|imagen/) end
Determines if the model supports vision (image/video) inputs @param model_id [String] the model identifier @return [Boolean] true if the model supports vision inputs
supports_vision?
ruby
crmne/ruby_llm
lib/ruby_llm/providers/gemini/capabilities.rb
https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/gemini/capabilities.rb
MIT
def supports_functions?(model_id) return false if model_id.match?(/text-embedding|embedding-001|aqa|flash-lite|imagen|gemini-2\.0-flash-lite/) model_id.match?(/gemini|pro|flash/) end
Determines if the model supports function calling @param model_id [String] the model identifier @return [Boolean] true if the model supports function calling
supports_functions?
ruby
crmne/ruby_llm
lib/ruby_llm/providers/gemini/capabilities.rb
https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/gemini/capabilities.rb
MIT
def supports_json_mode?(model_id) if model_id.match?(/text-embedding|embedding-001|aqa|imagen|gemini-2\.0-flash-lite|gemini-2\.5-pro-exp-03-25/) return false end model_id.match?(/gemini|pro|flash/) end
Determines if the model supports JSON mode @param model_id [String] the model identifier @return [Boolean] true if the model supports JSON mode
supports_json_mode?
ruby
crmne/ruby_llm
lib/ruby_llm/providers/gemini/capabilities.rb
https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/gemini/capabilities.rb
MIT
def format_display_name(model_id) model_id .delete_prefix('models/') .split('-') .map(&:capitalize) .join(' ') .gsub(/(\d+\.\d+)/, ' \1') # Add space before version numbers .gsub(/\s+/, ' ') # Clean up multiple spaces .gsub('Aqa', 'AQA') # Special case for AQA .strip end
Formats the model ID into a human-readable display name @param model_id [String] the model identifier @return [String] the formatted display name
format_display_name
ruby
crmne/ruby_llm
lib/ruby_llm/providers/gemini/capabilities.rb
https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/gemini/capabilities.rb
MIT
def supports_caching?(model_id) if model_id.match?(/flash-lite|gemini-2\.5-pro-exp-03-25|aqa|imagen|text-embedding|embedding-001/) return false end model_id.match?(/gemini|pro|flash/) end
Determines if the model supports context caching @param model_id [String] the model identifier @return [Boolean] true if the model supports caching
supports_caching?
ruby
crmne/ruby_llm
lib/ruby_llm/providers/gemini/capabilities.rb
https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/gemini/capabilities.rb
MIT
def model_type(model_id) case model_id when /text-embedding|embedding|gemini-embedding/ then 'embedding' when /imagen/ then 'image' else 'chat' end end
Returns the type of model (chat, embedding, image) @param model_id [String] the model identifier @return [String] the model type
model_type
ruby
crmne/ruby_llm
lib/ruby_llm/providers/gemini/capabilities.rb
https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/gemini/capabilities.rb
MIT
def model_family(model_id) case model_id when /gemini-2\.5-pro-exp-03-25/ then 'gemini25_pro_exp' when /gemini-2\.0-flash-lite/ then 'gemini20_flash_lite' when /gemini-2\.0-flash/ then 'gemini20_flash' when /gemini-1\.5-flash-8b/ then 'gemini15_flash_8b' when /gemini-1\.5-flash/ then 'gemini15_flash' when /gemini-1\.5-pro/ then 'gemini15_pro' when /gemini-embedding-exp/ then 'gemini_embedding_exp' when /text-embedding-004/ then 'embedding4' when /embedding-001/ then 'embedding1' when /aqa/ then 'aqa' when /imagen-3/ then 'imagen3' else 'other' end end
Returns the model family identifier @param model_id [String] the model identifier @return [String] the model family identifier
model_family
ruby
crmne/ruby_llm
lib/ruby_llm/providers/gemini/capabilities.rb
https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/gemini/capabilities.rb
MIT
def pricing_family(model_id) case model_id when /gemini-2\.5-pro-exp-03-25/ then :pro_2_5 # rubocop:disable Naming/VariableNumber when /gemini-2\.0-flash-lite/ then :flash_lite_2 # rubocop:disable Naming/VariableNumber when /gemini-2\.0-flash/ then :flash_2 # rubocop:disable Naming/VariableNumber when /gemini-1\.5-flash-8b/ then :flash_8b when /gemini-1\.5-flash/ then :flash when /gemini-1\.5-pro/ then :pro when /gemini-embedding-exp/ then :gemini_embedding when /text-embedding|embedding/ then :embedding when /imagen/ then :imagen when /aqa/ then :aqa else :base end end
Returns the pricing family identifier for the model @param model_id [String] the model identifier @return [Symbol] the pricing family identifier
pricing_family
ruby
crmne/ruby_llm
lib/ruby_llm/providers/gemini/capabilities.rb
https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/gemini/capabilities.rb
MIT
def default_input_price 0.075 # Default to Flash pricing end
Default input price for unknown models @return [Float] the default input price per million tokens
default_input_price
ruby
crmne/ruby_llm
lib/ruby_llm/providers/gemini/capabilities.rb
https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/gemini/capabilities.rb
MIT
def default_output_price 0.30 # Default to Flash pricing end
Default output price for unknown models @return [Float] the default output price per million tokens
default_output_price
ruby
crmne/ruby_llm
lib/ruby_llm/providers/gemini/capabilities.rb
https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/gemini/capabilities.rb
MIT
def extract_tool_calls(data) return nil unless data # Get the first candidate candidate = data.is_a?(Hash) ? data.dig('candidates', 0) : nil return nil unless candidate # Get the parts array from content parts = candidate.dig('content', 'parts') return nil unless parts.is_a?(Array) # Find the function call part function_call_part = parts.find { |p| p['functionCall'] } return nil unless function_call_part # Get the function call data function_data = function_call_part['functionCall'] return nil unless function_data # Create a unique ID for the tool call id = SecureRandom.uuid # Return the tool call in the expected format { id => ToolCall.new( id: id, name: function_data['name'], arguments: function_data['args'] ) } end
Extract tool calls from response data
extract_tool_calls
ruby
crmne/ruby_llm
lib/ruby_llm/providers/gemini/tools.rb
https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/gemini/tools.rb
MIT
def function_declaration_for(tool) { name: tool.name, description: tool.description, parameters: tool.parameters.any? ? format_parameters(tool.parameters) : nil }.compact end
Format a single tool for Gemini API
function_declaration_for
ruby
crmne/ruby_llm
lib/ruby_llm/providers/gemini/tools.rb
https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/gemini/tools.rb
MIT
def format_parameters(parameters) { type: 'OBJECT', properties: parameters.transform_values do |param| { type: param_type_for_gemini(param.type), description: param.description }.compact end, required: parameters.select { |_, p| p.required }.keys.map(&:to_s) } end
Format tool parameters for Gemini API
format_parameters
ruby
crmne/ruby_llm
lib/ruby_llm/providers/gemini/tools.rb
https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/gemini/tools.rb
MIT
def param_type_for_gemini(type) case type.to_s.downcase when 'integer', 'number', 'float' then 'NUMBER' when 'boolean' then 'BOOLEAN' when 'array' then 'ARRAY' when 'object' then 'OBJECT' else 'STRING' end end
Convert RubyLLM param types to Gemini API types
param_type_for_gemini
ruby
crmne/ruby_llm
lib/ruby_llm/providers/gemini/tools.rb
https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/gemini/tools.rb
MIT
def parse_email_at_notices_or_set_default return if params[:app].blank? val = params[:app][:email_at_notices] return if val.blank? # Sanitize negative values, split on comma, # strip, parse as integer, remove all '0's. # If empty, set as default and show an error message. email_at_notices = val .gsub(/-\d+/, "") .split(",") .map { |v| v.strip.to_i } .reject { |v| v == 0 } if email_at_notices.any? params[:app][:email_at_notices] = email_at_notices else default_array = params[:app][:email_at_notices] = Errbit::Config.email_at_notices flash[:error] = "Couldn't parse your notification frequency. Value was reset to default (#{default_array.join(", ")})." end end
email_at_notices is edited as a string, and stored as an array.
parse_email_at_notices_or_set_default
ruby
errbit/errbit
app/controllers/apps_controller.rb
https://github.com/errbit/errbit/blob/master/app/controllers/apps_controller.rb
MIT
def locate problem = Notice.find(params[:id]).problem redirect_to app_problem_path(problem.app, problem) end
Redirects a notice to the problem page. Useful when using User Information at Airbrake gem.
locate
ruby
errbit/errbit
app/controllers/notices_controller.rb
https://github.com/errbit/errbit/blob/master/app/controllers/notices_controller.rb
MIT
def grouped_lines lines.chunk do |line| line.in_app? || false end end
Group lines into sections of in-app files and external files
grouped_lines
ruby
errbit/errbit
app/decorators/backtrace_decorator.rb
https://github.com/errbit/errbit/blob/master/app/decorators/backtrace_decorator.rb
MIT
def icons return unless object.icons object.icons.reduce({}) do |c, (k, v)| c[k] = "data:#{v[0]};base64,#{Base64.encode64(v[1])}" c end end
return hash of icons as data URIs
icons
ruby
errbit/errbit
app/decorators/issue_tracker_type_decorator.rb
https://github.com/errbit/errbit/blob/master/app/decorators/issue_tracker_type_decorator.rb
MIT
def params_class(tracker) [(object.label == tracker.type_tracker) ? "chosen" : "", label].join(" ").strip end
class name for tracker type form fields 'chosen github' or 'bitbucket' for example
params_class
ruby
errbit/errbit
app/decorators/issue_tracker_type_decorator.rb
https://github.com/errbit/errbit/blob/master/app/decorators/issue_tracker_type_decorator.rb
MIT
def active_if_here(matches) current_controller = controller.controller_name.to_sym current_action = controller.action_name.to_sym sections = case matches when Hash matches when Array s = {} matches.each { |c| s[c] = :all } s else {matches => :all} end active = nil sections.each do |controller, actions| actions = Array(actions) active = " active" if current_controller == controller && (actions.include?(:all) || actions.include?(current_action)) end active end
Returns ' active' if you are on a given controller - active_if_here(:users) => ' active' if users controller Or on one of a list of controllers - active_if_here([:users, :blogs, :comments]) Or on certain action(s) in a certain controller - active_if_here(:users => :index, :blogs => [:create, :update], :comments) Useful for navigation elements that have a certain state when your on a given page. Returns nil if there are no matches so when passing: link_to 'link', '#', :class => active_if_here(:users) will not even set a class attribute if nil is passed back.
active_if_here
ruby
errbit/errbit
app/helpers/navigation_helper.rb
https://github.com/errbit/errbit/blob/master/app/helpers/navigation_helper.rb
MIT
def page_count_from_end(current_page, total_pages) (total_pages.to_i - current_page.to_i) + 1 end
Returns the page number in reverse order. Needed when reverse chronological paginating notices but want to display the actual chronological occurrence number. E.G. - Given 6 notices, page 2 shows the second from last occurrence indexed by 1, but it is displaying the 5th ever occurrence of that error.
page_count_from_end
ruby
errbit/errbit
app/helpers/navigation_helper.rb
https://github.com/errbit/errbit/blob/master/app/helpers/navigation_helper.rb
MIT
def execute nb_problem_outdated.tap do |nb| if nb > 0 criteria.each do |problem| ProblemDestroy.new(problem).execute end compact_database end end end
# Clear all problem not present for more than one week.
execute
ruby
errbit/errbit
app/interactors/outdated_problem_clearer.rb
https://github.com/errbit/errbit/blob/master/app/interactors/outdated_problem_clearer.rb
MIT
def initialize(user) @user = user end
@param user [User] User to destroy
initialize
ruby
errbit/errbit
app/interactors/user_destroy.rb
https://github.com/errbit/errbit/blob/master/app/interactors/user_destroy.rb
MIT
def initialize(mapping) @mapping = mapping @overrides = {} @storage = {} end
Create the Configurator object @param [Hash] mapping mapping of config names to environment value names @return [Configurator]
initialize
ruby
errbit/errbit
app/lib/configurator.rb
https://github.com/errbit/errbit/blob/master/app/lib/configurator.rb
MIT
def scan @mapping.each do |key, values| @overrides[key] = values.pop if values.last.is_a? Proc env_name = values.find { |v| ENV[v] } @storage[key] = if env_name ENV[env_name].empty? ? "" : YAML.parse(ENV[env_name]).to_ruby end end end
Process the environment variable values and store the overrides
scan
ruby
errbit/errbit
app/lib/configurator.rb
https://github.com/errbit/errbit/blob/master/app/lib/configurator.rb
MIT
def read @storage = {} scan apply_overrides OpenStruct.new(@storage) end
Perform all the required processing and return the configuration object @return [OpenStruct] configuration object
read
ruby
errbit/errbit
app/lib/configurator.rb
https://github.com/errbit/errbit/blob/master/app/lib/configurator.rb
MIT
def find_or_create_err!(attrs) err = Err.where(fingerprint: attrs[:fingerprint]).first return err if err problem = problems.create!( error_class: attrs[:error_class], environment: attrs[:environment], app_name: name ) problem.errs.create!(attrs.slice(:fingerprint, :problem_id)) end
Accepts a hash with the following attributes: * <tt>:error_class</tt> - the class of error (required to create a new Problem) * <tt>:environment</tt> - the environment the source app was running in (required to create a new Problem) * <tt>:fingerprint</tt> - a unique value identifying the notice
find_or_create_err!
ruby
errbit/errbit
app/models/app.rb
https://github.com/errbit/errbit/blob/master/app/models/app.rb
MIT
def copy_attributes_from(app_id) copy_app = App.where(_id: app_id).first return if copy_app.blank? # Copy fields (copy_app.fields.keys - ["_id", "name", "created_at", "updated_at"]).each do |k| send("#{k}=", copy_app.send(k)) end # Clone the embedded objects that can be changed via apps/edit (ignore errs, etc.) ["watchers", "issue_tracker", "notification_service"].each do |relation| if (obj = copy_app.send(relation)) send("#{relation}=", obj.is_a?(Array) ? obj.map(&:clone) : obj.clone) end end end
Copy app attributes from another app.
copy_attributes_from
ruby
errbit/errbit
app/models/app.rb
https://github.com/errbit/errbit/blob/master/app/models/app.rb
MIT
def cache_attributes_on_problem @problem = Problem.cache_notice(@error.problem_id, @notice) end
Update problem cache with information about this notice
cache_attributes_on_problem
ruby
errbit/errbit
app/models/error_report.rb
https://github.com/errbit/errbit/blob/master/app/models/error_report.rb
MIT
def services_notification return unless app.notification_service_configured? && should_notify? app.notification_service.create_notification(problem) rescue => e HoptoadNotifier.notify(e) end
Launch all notification define on the app associate to this notice
services_notification
ruby
errbit/errbit
app/models/error_report.rb
https://github.com/errbit/errbit/blob/master/app/models/error_report.rb
MIT
def error @error ||= app.find_or_create_err!( error_class: error_class, environment: rails_env, fingerprint: fingerprint ) end
# Error associate to this error_report Can already exist or not @return [ Error ]
error
ruby
errbit/errbit
app/models/error_report.rb
https://github.com/errbit/errbit/blob/master/app/models/error_report.rb
MIT
def validate_tracker (tracker.errors || {}).each do |k, v| errors.add k, v end end
Allow the tracker to validate its own params
validate_tracker
ruby
errbit/errbit
app/models/issue_tracker.rb
https://github.com/errbit/errbit/blob/master/app/models/issue_tracker.rb
MIT
def filtered_message message.gsub(/(#<.+?):[0-9a-f]x[0-9a-f]+(>)/, '\1\2') end
filter memory addresses out of object strings example: "#<Object:0x007fa2b33d9458>" becomes "#<Object>"
filtered_message
ruby
errbit/errbit
app/models/notice.rb
https://github.com/errbit/errbit/blob/master/app/models/notice.rb
MIT
def denormalize App.each do |app| f = app.notice_fingerprinter next if f.source && f.source != CONFIG_SOURCE_SITE app.update(notice_fingerprinter: notice_fingerprinter_attributes) end end
Denormalize SiteConfig onto individual apps so that this record doesn't need to be accessed when inserting new error notices
denormalize
ruby
errbit/errbit
app/models/site_config.rb
https://github.com/errbit/errbit/blob/master/app/models/site_config.rb
MIT
def check_params if service_url.blank? errors.add :service_url, "You must specify your Slack Hook url" end if room_id.present? && !CHANNEL_NAME_REGEXP.match(room_id) errors.add :room_id, "Slack channel name must be lowercase, with no space, special character, or periods." end end
Make room_id optional in case users want to use the default channel setup on Slack when creating the webhook
check_params
ruby
errbit/errbit
app/models/notification_services/slack_service.rb
https://github.com/errbit/errbit/blob/master/app/models/notification_services/slack_service.rb
MIT
def initialize(user, record) raise Pundit::NotAuthorizedError, "must be logged in" if user.blank? @user = user @record = record end
@param user [User] The user making the request @param record [Mongoid::Document] The record being accessed
initialize
ruby
errbit/errbit
app/policies/application_policy.rb
https://github.com/errbit/errbit/blob/master/app/policies/application_policy.rb
MIT
def initialize(user, scope) raise Pundit::NotAuthorizedError, "must be logged in" if user.blank? @user = user @scope = scope end
@param user [User] @param scope [Object] The scope of records being accessed
initialize
ruby
errbit/errbit
app/policies/application_policy.rb
https://github.com/errbit/errbit/blob/master/app/policies/application_policy.rb
MIT
def recurse(*types, &block) types = [self.class] if types.empty? h = inject({}) do |hash, (key, value)| case value when *types hash[key] = value.recurse(*types, &block) else hash[key] = value end hash end yield h end
Apply a block to hash, and recursively apply that block to each sub-hash or +types+. h = {:a=>1, :b=>{:b1=>1, :b2=>2}} g = h.recurse{|h| h.inject({}){|h,(k,v)| h[k.to_s] = v; h} } g #=> {"a"=>1, "b"=>{"b1"=>1, "b2"=>2}}
recurse
ruby
errbit/errbit
config/initializers/hash.rb
https://github.com/errbit/errbit/blob/master/config/initializers/hash.rb
MIT
def render(view) view.content_tag(name, attributes[:content], prepare_attributes(attributes.except(:content))) end
Render tag into a Rails view. @param [ActionView::Base] view instance of a Rails view. @return [String] HTML string for the tag.
render
ruby
kpumuk/meta-tags
lib/meta_tags/content_tag.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/content_tag.rb
MIT
def render(*args, &block) meta_tags[:title] = @page_title if defined?(@page_title) && @page_title meta_tags[:keywords] = @page_keywords if defined?(@page_keywords) && @page_keywords meta_tags[:description] = @page_description if defined?(@page_description) && @page_description super end
Processes the <tt>@page_title</tt>, <tt>@page_keywords</tt>, and <tt>@page_description</tt> instance variables and calls +render+.
render
ruby
kpumuk/meta-tags
lib/meta_tags/controller_helper.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/controller_helper.rb
MIT
def meta_tags @meta_tags ||= MetaTagsCollection.new end
Get meta tags for the page.
meta_tags
ruby
kpumuk/meta-tags
lib/meta_tags/controller_helper.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/controller_helper.rb
MIT
def update(object = {}) meta_tags = if object.respond_to?(:to_meta_tags) # @type var object: _MetaTagish & Object object.to_meta_tags else # @type var object: Hash[String | Symbol, untyped] object end @meta_tags.deep_merge! normalize_open_graph(meta_tags) end
Recursively merges a Hash of meta tag attributes into current list. @param [Hash, #to_meta_tags] object Hash of meta tags (or object responding to #to_meta_tags and returning a hash) to merge into the current list. @return [Hash] result of the merge.
update
ruby
kpumuk/meta-tags
lib/meta_tags/meta_tags_collection.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/meta_tags_collection.rb
MIT
def with_defaults(defaults = {}) old_meta_tags = @meta_tags @meta_tags = normalize_open_graph(defaults).deep_merge!(@meta_tags) yield ensure @meta_tags = old_meta_tags end
Temporary merges defaults with current meta tags list and yields the block. @param [Hash] defaults list of default meta tag attributes. @return result of the block call.
with_defaults
ruby
kpumuk/meta-tags
lib/meta_tags/meta_tags_collection.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/meta_tags_collection.rb
MIT
def full_title(defaults = {}) with_defaults(defaults) { extract_full_title } end
Constructs the full title as if it would be rendered in title meta tag. @param [Hash] defaults list of default meta tag attributes. @return [String] page title.
full_title
ruby
kpumuk/meta-tags
lib/meta_tags/meta_tags_collection.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/meta_tags_collection.rb
MIT
def page_title(defaults = {}) old_site = @meta_tags[:site] @meta_tags[:site] = nil full_title = with_defaults(defaults) { extract_full_title } full_title.presence || old_site || "" ensure @meta_tags[:site] = old_site end
Constructs the title without site title (for normalized parameters). When title is empty, use the site title instead. @return [String] page title.
page_title
ruby
kpumuk/meta-tags
lib/meta_tags/meta_tags_collection.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/meta_tags_collection.rb
MIT
def delete(*names) names.each { |name| @meta_tags.delete(name) } end
Deletes specified meta tags. @param [Array<String, Symbol>] names a list of meta tags to delete.
delete
ruby
kpumuk/meta-tags
lib/meta_tags/meta_tags_collection.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/meta_tags_collection.rb
MIT
def extract_full_title site_title = extract(:site) || "" title = extract_title separator = extract_separator reverse = extract(:reverse) == true TextNormalizer.normalize_title(site_title, title, separator, reverse) end
Extracts full page title and deletes all related meta tags. @return [String] page title.
extract_full_title
ruby
kpumuk/meta-tags
lib/meta_tags/meta_tags_collection.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/meta_tags_collection.rb
MIT
def extract_title title = extract(:title).presence return [] unless title # @type var title: Array[String] title = Array(title) return title.map(&:downcase) if extract(:lowercase) == true title end
Extracts page title as an array of segments without site title and separators. @return [Array<String>] segments of page title.
extract_title
ruby
kpumuk/meta-tags
lib/meta_tags/meta_tags_collection.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/meta_tags_collection.rb
MIT
def extract_separator if meta_tags[:separator] == false # Special case: if separator is hidden, do not display suffix/prefix prefix = separator = suffix = "" else prefix = extract_separator_section(:prefix, " ") separator = extract_separator_section(:separator, "|") suffix = extract_separator_section(:suffix, " ") end delete(:separator, :prefix, :suffix) TextNormalizer.safe_join([prefix, separator, suffix], "") end
Extracts title separator as a string. @return [String] page title separator.
extract_separator
ruby
kpumuk/meta-tags
lib/meta_tags/meta_tags_collection.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/meta_tags_collection.rb
MIT
def extract_robots result = Hash.new { |h, k| h[k] = [] } [ # noindex has higher priority than index [:noindex, :index], # follow has higher priority than nofollow [:follow, :nofollow], :noarchive ].each do |attributes| calculate_robots_attributes(result, attributes) end result.transform_values { |v| v.join(", ") } end
Extracts noindex settings as a Hash mapping noindex tag name to value. @return [Hash<String,String>] noindex attributes.
extract_robots
ruby
kpumuk/meta-tags
lib/meta_tags/meta_tags_collection.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/meta_tags_collection.rb
MIT
def normalize_open_graph(meta_tags) meta_tags = meta_tags.with_indifferent_access meta_tags[:og] = meta_tags.delete(:open_graph) if meta_tags.key?(:open_graph) meta_tags end
Converts input hash to HashWithIndifferentAccess and renames :open_graph to :og. @param [Hash] meta_tags list of meta tags. @return [ActiveSupport::HashWithIndifferentAccess] normalized meta tags list.
normalize_open_graph
ruby
kpumuk/meta-tags
lib/meta_tags/meta_tags_collection.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/meta_tags_collection.rb
MIT
def extract_separator_section(name, default) (meta_tags[name] == false) ? "" : (meta_tags[name] || default) end
Extracts separator segment without deleting it from meta tags list. If the value is false, empty string will be returned. @param [Symbol, String] name separator segment name. @param [String] default default value. @return [String] separator segment value.
extract_separator_section
ruby
kpumuk/meta-tags
lib/meta_tags/meta_tags_collection.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/meta_tags_collection.rb
MIT
def extract_robots_attribute(name) noindex = extract(name) noindex_name = (noindex.is_a?(String) || noindex.is_a?(Array)) ? noindex : "robots" noindex_value = noindex ? name.to_s : nil [noindex_name, noindex_value] end
Extracts robots attribute (noindex, nofollow, etc) name and value. @param [String, Symbol] name noindex attribute name. @return [Array<String>] pair of noindex attribute name and value.
extract_robots_attribute
ruby
kpumuk/meta-tags
lib/meta_tags/meta_tags_collection.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/meta_tags_collection.rb
MIT
def initialize(meta_tags) @meta_tags = meta_tags @normalized_meta_tags = {} end
Initialized a new instance of Renderer. @param [MetaTagsCollection] meta_tags meta tags object to render.
initialize
ruby
kpumuk/meta-tags
lib/meta_tags/renderer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/renderer.rb
MIT
def render(view) tags = [] # : Array[Tag] render_charset(tags) render_title(tags) render_icon(tags) render_with_normalization(tags, :description) render_with_normalization(tags, :keywords) render_refresh(tags) render_canonical_link(tags) render_noindex(tags) render_alternate(tags) render_open_search(tags) render_links(tags) render_hashes(tags) render_custom(tags) rendered_tags = tags.tap(&:compact!).map { |tag| tag.render(view) } view.safe_join rendered_tags, MetaTags.config.minify_output ? "" : "\n" end
Renders meta tags on the page. @param [ActionView::Base] view Rails view object.
render
ruby
kpumuk/meta-tags
lib/meta_tags/renderer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/renderer.rb
MIT
def render_charset(tags) charset = meta_tags.extract(:charset) tags << Tag.new(:meta, charset: charset) if charset.present? end
Renders charset tag. @param [Array<Tag>] tags a buffer object to store tag in.
render_charset
ruby
kpumuk/meta-tags
lib/meta_tags/renderer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/renderer.rb
MIT
def render_title(tags) normalized_meta_tags[:title] = meta_tags.page_title normalized_meta_tags[:site] = meta_tags[:site] title = meta_tags.extract_full_title normalized_meta_tags[:full_title] = title default_attributes = MetaTags.config.title_tag_attributes || {} if title.present? tags << ContentTag.new(:title, {content: title}.with_defaults(default_attributes)) end end
Renders title tag. @param [Array<Tag>] tags a buffer object to store tag in.
render_title
ruby
kpumuk/meta-tags
lib/meta_tags/renderer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/renderer.rb
MIT
def render_icon(tags) icon = meta_tags.extract(:icon) return unless icon # String? Value is an href icon = [{href: icon}] if icon.is_a?(String) # Hash? Single icon instead of a list of icons icon = [icon] if icon.is_a?(Hash) icon.each do |icon_params| icon_params = {rel: "icon", type: "image/x-icon"}.with_indifferent_access.merge(icon_params) tags << Tag.new(:link, icon_params) end end
Renders icon(s) tag. @param [Array<Tag>] tags a buffer object to store tag in.
render_icon
ruby
kpumuk/meta-tags
lib/meta_tags/renderer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/renderer.rb
MIT
def render_with_normalization(tags, name) value = TextNormalizer.public_send(:"normalize_#{name}", meta_tags.extract(name)) normalized_meta_tags[name] = value tags << Tag.new(:meta, name: name, content: value) if value.present? end
Renders meta tag with normalization (should have a corresponding normalize_ method in TextNormalizer). @param [Array<Tag>] tags a buffer object to store tag in. @see TextNormalizer
render_with_normalization
ruby
kpumuk/meta-tags
lib/meta_tags/renderer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/renderer.rb
MIT
def render_noindex(tags) meta_tags.extract_robots.each do |name, content| tags << Tag.new(:meta, name: name, content: content) if content.present? end end
Renders noindex and nofollow meta tags. @param [Array<Tag>] tags a buffer object to store tag in.
render_noindex
ruby
kpumuk/meta-tags
lib/meta_tags/renderer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/renderer.rb
MIT
def render_refresh(tags) refresh = meta_tags.extract(:refresh) tags << Tag.new(:meta, "http-equiv" => "refresh", :content => refresh.to_s) if refresh.present? end
Renders refresh meta tag. @param [Array<Tag>] tags a buffer object to store tag in.
render_refresh
ruby
kpumuk/meta-tags
lib/meta_tags/renderer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/renderer.rb
MIT
def render_alternate(tags) alternate = meta_tags.extract(:alternate) return unless alternate if alternate.is_a?(Hash) alternate.each do |hreflang, href| tags << Tag.new(:link, rel: "alternate", href: href, hreflang: hreflang) if href.present? end elsif alternate.is_a?(Array) alternate.each do |link_params| tags << Tag.new(:link, {rel: "alternate"}.with_indifferent_access.merge(link_params)) end end end
Renders alternate link tags. @param [Array<Tag>] tags a buffer object to store tag in.
render_alternate
ruby
kpumuk/meta-tags
lib/meta_tags/renderer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/renderer.rb
MIT
def render_open_search(tags) open_search = meta_tags.extract(:open_search) return unless open_search href = open_search[:href] title = open_search[:title] type = "application/opensearchdescription+xml" tags << Tag.new(:link, rel: "search", type: type, href: href, title: title) if href.present? end
Renders open_search link tag. @param [Array<Tag>] tags a buffer object to store tag in.
render_open_search
ruby
kpumuk/meta-tags
lib/meta_tags/renderer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/renderer.rb
MIT
def render_links(tags) [:amphtml, :prev, :next, :image_src, :manifest].each do |tag_name| href = meta_tags.extract(tag_name) if href.present? @normalized_meta_tags[tag_name] = href tags << Tag.new(:link, rel: tag_name, href: href) end end end
Renders links. @param [Array<Tag>] tags a buffer object to store tag in.
render_links
ruby
kpumuk/meta-tags
lib/meta_tags/renderer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/renderer.rb
MIT
def render_canonical_link(tags) href = meta_tags.extract(:canonical) # extract, so its not used anywhere else return if MetaTags.config.skip_canonical_links_on_noindex && meta_tags[:noindex] return if href.blank? @normalized_meta_tags[:canonical] = href tags << Tag.new(:link, rel: :canonical, href: href) end
Renders canonical link @param [Array<Tag>] tags a buffer object to store tag in.
render_canonical_link
ruby
kpumuk/meta-tags
lib/meta_tags/renderer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/renderer.rb
MIT
def render_hashes(tags, **opts) meta_tags.meta_tags.each_key do |property| render_hash(tags, property, **opts) end end
Renders complex hash objects. @param [Array<Tag>] tags a buffer object to store tag in.
render_hashes
ruby
kpumuk/meta-tags
lib/meta_tags/renderer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/renderer.rb
MIT
def render_hash(tags, key, **opts) data = meta_tags.meta_tags[key] return unless data.is_a?(Hash) process_hash(tags, key, data, **opts) meta_tags.extract(key) end
Renders a complex hash object by key. @param [Array<Tag>] tags a buffer object to store tag in.
render_hash
ruby
kpumuk/meta-tags
lib/meta_tags/renderer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/renderer.rb
MIT
def render_custom(tags) meta_tags.meta_tags.each do |name, data| Array(data).each do |val| tags << Tag.new(:meta, configured_name_key(name) => name, :content => val) end meta_tags.extract(name) end end
Renders custom meta tags. @param [Array<Tag>] tags a buffer object to store tag in.
render_custom
ruby
kpumuk/meta-tags
lib/meta_tags/renderer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/renderer.rb
MIT
def process_tree(tags, property, content, itemprop: nil, **opts) method = case content when Hash :process_hash when Array :process_array else iprop = itemprop :render_tag end __send__(method, tags, property, content, itemprop: iprop, **opts) end
Recursive method to process all the hashes and arrays on meta tags @param [Array<Tag>] tags a buffer object to store tag in. @param [String, Symbol] property a Hash or a String to render as meta tag. @param [Hash, Array, String, Symbol] content text content or a symbol reference to top-level meta tag.
process_tree
ruby
kpumuk/meta-tags
lib/meta_tags/renderer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/renderer.rb
MIT
def process_hash(tags, property, content, **opts) itemprop = content.delete(:itemprop) content.each do |key, value| if key.to_s == "_" iprop = itemprop key = property else key = "#{property}:#{key}" end normalized_value = if value.is_a?(Symbol) normalized_meta_tags[value] else value end process_tree(tags, key, normalized_value, **opts.merge(itemprop: iprop)) end end
Recursive method to process a hash with meta tags @param [Array<Tag>] tags a buffer object to store tag in. @param [String, Symbol] property a Hash or a String to render as meta tag. @param [Hash] content nested meta tag attributes.
process_hash
ruby
kpumuk/meta-tags
lib/meta_tags/renderer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/renderer.rb
MIT
def process_array(tags, property, content, **opts) content.each { |v| process_tree(tags, property, v, **opts) } end
Recursive method to process a hash with meta tags @param [Array<Tag>] tags a buffer object to store tag in. @param [String, Symbol] property a Hash or a String to render as meta tag. @param [Array] content array of nested meta tag attributes or values.
process_array
ruby
kpumuk/meta-tags
lib/meta_tags/renderer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/renderer.rb
MIT
def render_tag(tags, name, value, itemprop: nil) name_key ||= configured_name_key(name) tags << Tag.new(:meta, name_key => name.to_s, :content => value, :itemprop => itemprop) if value.present? end
Recursive method to process a hash with meta tags @param [Array<Tag>] tags a buffer object to store tag in. @param [String, Symbol] name a Hash or a String to render as meta tag. @param [String, Symbol] value text content or a symbol reference to top-level meta tag. @param [String, Symbol] itemprop value of the itemprop attribute.
render_tag
ruby
kpumuk/meta-tags
lib/meta_tags/renderer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/renderer.rb
MIT
def configured_name_key(name) is_property_tag = MetaTags.config.property_tags.any? do |tag_name| name.to_s.match(/^#{Regexp.escape(tag_name.to_s)}\b/) end is_property_tag ? :property : :name end
Returns meta tag property name for a give meta tag based on the configured list of property tags in MetaTags::Configuration#property_tags. @param [String, Symbol] name tag key. @return [Symbol] meta tag attribute name (:property or :name).
configured_name_key
ruby
kpumuk/meta-tags
lib/meta_tags/renderer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/renderer.rb
MIT
def initialize(name, attributes = {}) @name = name.to_s @attributes = attributes end
Initializes a new instance of Tag class. @param [String, Symbol] name HTML tag name @param [Hash] attributes list of HTML tag attributes
initialize
ruby
kpumuk/meta-tags
lib/meta_tags/tag.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/tag.rb
MIT
def render(view) view.tag(name, prepare_attributes(attributes), MetaTags.config.open_meta_tags?) end
Render tag into a Rails view. @param [ActionView::Base] view instance of a Rails view. @return [String] HTML string for the tag.
render
ruby
kpumuk/meta-tags
lib/meta_tags/tag.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/tag.rb
MIT
def normalize_title(site_title, title, separator, reverse = false) clean_title = cleanup_strings(title) clean_title.reverse! if reverse site_title = cleanup_string(site_title) separator = cleanup_string(separator, strip: false) # Truncate title and site title site_title, clean_title = truncate_title(site_title, clean_title, separator) if site_title.present? if reverse clean_title.push(site_title) else clean_title.unshift(site_title) end end safe_join(clean_title, separator) end
Normalize title value. @param [String] site_title site title. @param [Array<String>] title title string. @param [String] separator a string to join title parts with. @param [true,false] reverse whether title should be reversed. @return [String] title with HTML tags removed.
normalize_title
ruby
kpumuk/meta-tags
lib/meta_tags/text_normalizer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/text_normalizer.rb
MIT
def normalize_description(description) # description could be another object not a string, but since it probably # serves the same purpose we could just as it to convert itself to str # and continue from there description = cleanup_string(description) return "" if description.blank? truncate(description, MetaTags.config.description_limit) end
Normalize description value. @param [String] description description string. @return [String] text with tags removed, squashed spaces, truncated to 200 characters.
normalize_description
ruby
kpumuk/meta-tags
lib/meta_tags/text_normalizer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/text_normalizer.rb
MIT
def normalize_keywords(keywords) keywords = cleanup_strings(keywords) return "" if keywords.blank? keywords.each(&:downcase!) if MetaTags.config.keywords_lowercase separator = cleanup_string MetaTags.config.keywords_separator, strip: false keywords = truncate_array(keywords, MetaTags.config.keywords_limit, separator) safe_join(keywords, separator) end
Normalize keywords value. @param [String, Array<String>] keywords list of keywords as a string or Array. @return [String] list of keywords joined with comma, with tags removed.
normalize_keywords
ruby
kpumuk/meta-tags
lib/meta_tags/text_normalizer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/text_normalizer.rb
MIT
def strip_tags(string) if defined?(Loofah) # Instead of strip_tags we will use Loofah to strip tags from now on Loofah.fragment(string).text(encode_special_chars: false) else helpers.strip_tags(string) end end
Strips all HTML tags from the +html+, including comments. @param [String] string HTML string. @return [String] html_safe string with no HTML tags.
strip_tags
ruby
kpumuk/meta-tags
lib/meta_tags/text_normalizer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/text_normalizer.rb
MIT
def safe_join(array, sep = $OFS) helpers.safe_join(array, sep) end
This method returns a html safe string similar to what <tt>Array#join</tt> would return. All items in the array, including the supplied separator, are html escaped unless they are html safe, and the returned string is marked as html safe. @param [Array<String>] array list of strings to join. @param [String] sep separator to join strings with. @return [String] input strings joined together using a given separator.
safe_join
ruby
kpumuk/meta-tags
lib/meta_tags/text_normalizer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/text_normalizer.rb
MIT
def cleanup_string(string, strip: true) return "" if string.nil? raise ArgumentError, "Expected a string or an object that implements #to_str" unless string.respond_to?(:to_str) s = strip_tags(string.to_str) s = s.dup if s.frozen? s.gsub!(/\s+/, " ") s.strip! if strip s end
Removes HTML tags and squashes down all the spaces. @param [String, nil] string input string. @return [String] input string with no HTML tags and consequent white space characters squashed into a single space.
cleanup_string
ruby
kpumuk/meta-tags
lib/meta_tags/text_normalizer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/text_normalizer.rb
MIT
def cleanup_strings(strings, strip: true) strings = Array(strings).flatten.map! { |s| cleanup_string(s, strip: strip) } strings.reject!(&:blank?) strings end
Cleans multiple strings up. @param [String, Array<String>] strings input string(s). @return [Array<String>] clean strings. @see cleanup_string
cleanup_strings
ruby
kpumuk/meta-tags
lib/meta_tags/text_normalizer.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/text_normalizer.rb
MIT
def meta_tags @meta_tags ||= MetaTagsCollection.new end
Get meta tags for the page.
meta_tags
ruby
kpumuk/meta-tags
lib/meta_tags/view_helper.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/view_helper.rb
MIT
def title(title = nil, headline = "") set_meta_tags(title: title) unless title.nil? headline.presence || meta_tags[:title] end
Set the page title and return it back. This method is best suited for use in helpers. It sets the page title and returns it (or +headline+ if specified). @param [nil, String, Array] title page title. When passed as an +Array+, parts will be joined using configured separator value (see {#display_meta_tags}). When nil, current title will be returned. @param [String] headline the value to return from method. Useful for using this method in views to set both page title and the content of heading tag. @return [String] returns +title+ value or +headline+ if passed. @example Set HTML title to "Please login", return "Please login" title 'Login Page' @example Set HTML title to "Login Page", return "Please login" title 'Login Page', 'Please login' @example Set title as array of strings title title: ['part1', 'part2'] # => "part1 | part2" @example Get current title title @see #display_meta_tags
title
ruby
kpumuk/meta-tags
lib/meta_tags/view_helper.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/view_helper.rb
MIT
def keywords(keywords) set_meta_tags(keywords: keywords) keywords end
Set the page keywords. @param [String, Array] keywords meta keywords to render in HEAD section of the HTML document. @return [String, Array] passed value. @example keywords 'keyword1, keyword2' keywords %w(keyword1 keyword2) @see #display_meta_tags
keywords
ruby
kpumuk/meta-tags
lib/meta_tags/view_helper.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/view_helper.rb
MIT
def description(description) set_meta_tags(description: description) description end
Set the page description. @param [String] description page description to be set in HEAD section of the HTML document. Please note, any HTML tags will be stripped from output string, and string will be truncated to 200 characters. @return [String] passed value. @example description 'This is login page' @see #display_meta_tags
description
ruby
kpumuk/meta-tags
lib/meta_tags/view_helper.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/view_helper.rb
MIT
def noindex(noindex = true) set_meta_tags(noindex: noindex) noindex end
Set the noindex meta tag @param [Boolean, String, Array<String>] noindex a noindex value. @return [Boolean, String, Array<String>] passed value. @example noindex true noindex 'googlebot' @see #display_meta_tags
noindex
ruby
kpumuk/meta-tags
lib/meta_tags/view_helper.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/view_helper.rb
MIT
def nofollow(nofollow = true) set_meta_tags(nofollow: nofollow) nofollow end
Set the nofollow meta tag @param [Boolean, String, Array<String>] nofollow a nofollow value. @return [Boolean, String, Array<String>] passed value. @example nofollow true nofollow 'googlebot' @see #display_meta_tags
nofollow
ruby
kpumuk/meta-tags
lib/meta_tags/view_helper.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/view_helper.rb
MIT
def refresh(refresh) set_meta_tags(refresh: refresh) refresh end
Set the refresh meta tag @param [Integer, String] refresh a refresh value. @return [Integer, String] passed value. @example refresh 5 refresh "5;url=http://www.example.com/" @see #display_meta_tags
refresh
ruby
kpumuk/meta-tags
lib/meta_tags/view_helper.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/view_helper.rb
MIT
def display_meta_tags(defaults = {}) meta_tags.with_defaults(defaults) { Renderer.new(meta_tags).render(self) } end
Set default meta tag values and display meta tags. This method should be used in layout file. @param [Hash] defaults default meta tag values. @option default [String] :site (nil) site title; @option default [String] :title ("") page title; @option default [String] :description (nil) page description; @option default [String] :keywords (nil) page keywords; @option default [String, Boolean] :prefix (" ") text between site name and separator; when +false+, no prefix will be rendered; @option default [String] :separator ("|") text used to separate website name from page title; @option default [String, Boolean] :suffix (" ") text between separator and page title; when +false+, no suffix will be rendered; @option default [Boolean] :lowercase (false) when true, the page title will be lowercase; @option default [Boolean] :reverse (false) when true, the page and site names will be reversed; @option default [Boolean, String] :noindex (false) add noindex meta tag; when true, 'robots' will be used, otherwise the string will be used; @option default [Boolean, String] :nofollow (false) add nofollow meta tag; when true, 'robots' will be used, otherwise the string will be used; @option default [String] :canonical (nil) add canonical link tag. @option default [Hash] :alternate ({}) add alternate link tag. @option default [String] :prev (nil) add prev link tag; @option default [String] :next (nil) add next link tag. @option default [String, Integer] :refresh (nil) meta refresh tag; @option default [Hash] :open_graph ({}) add Open Graph meta tags. @option default [Hash] :open_search ({}) add Open Search link tag. @return [String] HTML meta tags to render in HEAD section of the HTML document. @example <head> <%= display_meta_tags site: 'My website' %> </head>
display_meta_tags
ruby
kpumuk/meta-tags
lib/meta_tags/view_helper.rb
https://github.com/kpumuk/meta-tags/blob/master/lib/meta_tags/view_helper.rb
MIT
def establish_remote_server fail "establish_remote_server called with remote established" if @remote commands = ProxyMachine.router.call(@buffer.join) LOGGER.info "#{peer} #{commands.inspect}" close_connection unless commands.instance_of?(Hash) if remote = commands[:remote] m, host, port = *remote.match(/^(.+):(.+)$/) @remote = [host, port] if data = commands[:data] @buffer = [data] end if reply = commands[:reply] send_data(reply) end @connect_timeout = commands[:connect_timeout] @inactivity_timeout = commands[:inactivity_timeout] connect_to_server elsif close = commands[:close] if close == true close_connection else send_data(close) close_connection_after_writing end elsif commands[:noop] # do nothing else close_connection end end
Called when new data is available from the client but no remote server has been established. If a remote can be established, an attempt is made to connect and proxy to the remote server.
establish_remote_server
ruby
mojombo/proxymachine
lib/proxymachine/client_connection.rb
https://github.com/mojombo/proxymachine/blob/master/lib/proxymachine/client_connection.rb
MIT
def server_connection_success LOGGER.info "Successful connection to #{@remote.join(':')}" @connected = true @buffer.each { |data| @server_side.send_data(data) } @buffer = [] proxy_incoming_to(@server_side, 10240) end
Called by the server side immediately after the server connection was successfully established. Send any buffer we've accumulated and start raw proxying.
server_connection_success
ruby
mojombo/proxymachine
lib/proxymachine/client_connection.rb
https://github.com/mojombo/proxymachine/blob/master/lib/proxymachine/client_connection.rb
MIT
def server_connection_failed @server_side = nil if @connected LOGGER.error "Connection with #{@remote.join(':')} was terminated prematurely." close_connection ProxyMachine.connect_error_callback.call(@remote.join(':')) elsif @tries < 10 @tries += 1 LOGGER.warn "Retrying connection with #{@remote.join(':')} (##{@tries})" EM.add_timer(0.1) { connect_to_server } else LOGGER.error "Connect #{@remote.join(':')} failed after ten attempts." close_connection ProxyMachine.connect_error_callback.call(@remote.join(':')) end end
Called by the server side when a connection could not be established, either due to a hard connection failure or to a connection timeout. Leave the client connection open and retry the server connection up to 10 times.
server_connection_failed
ruby
mojombo/proxymachine
lib/proxymachine/client_connection.rb
https://github.com/mojombo/proxymachine/blob/master/lib/proxymachine/client_connection.rb
MIT
def server_inactivity_timeout(timeout, elapsed) LOGGER.error "Disconnecting #{@remote.join(':')} after #{elapsed}s of inactivity (> #{timeout.inspect})" @server_side = nil close_connection ProxyMachine.inactivity_error_callback.call(@remote.join(':')) end
Called by the server when an inactivity timeout is detected. The timeout argument is the configured inactivity timeout in seconds as a float; the elapsed argument is the amount of time that actually elapsed since connecting but not receiving any data.
server_inactivity_timeout
ruby
mojombo/proxymachine
lib/proxymachine/client_connection.rb
https://github.com/mojombo/proxymachine/blob/master/lib/proxymachine/client_connection.rb
MIT
def xml_to_hash(xml) policy = { 'Appx' => { 'rules' => [] }, 'Dll' => { 'rules' => [] }, 'Exe' => { 'rules' => [] }, 'Msi' => { 'rules' => [] }, 'Script' => { 'rules' => [] }, } xml.root.children.each do |elem| next unless elem.is_a?(Nokogiri::XML::Element) policy[elem['Type']]['mode'] = elem['EnforcementMode'] # First get the metadata about each rule elem.children.each do |rule| # We only process rules we have definitions for next unless APPLOCKER_TYPE_MAP.key? rule.node_name type = APPLOCKER_TYPE_MAP[rule.name] pol_rule = { 'type' => type, 'name' => rule['Name'], 'id' => rule['Id'], 'action' => rule['Action'], 'description' => rule['Description'], 'user_or_group_sid' => rule['UserOrGroupSid'], } conditions = [] # each rule has a `Condition` section, and there may be more than 1 rule.children.each do |app_conditions| app_conditions.children.each do |condition| case type when 'path' next if condition['Path'].nil? conditions << { 'path' => condition['Path'] } when 'hash' condition.children.each do |filehash| next if filehash['Data'].nil? conditions << { 'type' => filehash['Type'], 'data' => filehash['Data'], 'file_name' => filehash['SourceFileName'], 'file_length' => filehash['SourceFileLength'], } end when 'certificate' next if condition['PublisherName'].nil? bin_publisher = { 'publisher' => condition['PublisherName'], 'product_name' => condition['ProductName'], 'binary_name' => condition['BinaryName'], } # Get all of the binary version information condition.children.each do |binver| next if binver['LowSection'].nil? bin_publisher['binary_version'] = {} bin_publisher['binary_version']['low'] = binver['LowSection'] bin_publisher['binary_version']['high'] = binver[ 'HighSection' ] end conditions << bin_publisher end end end pol_rule['conditions'] = conditions # And add the constructed rule to our ruleset policy[elem['Type']]['rules'] << pol_rule end end policy end
Given an XML config from AppLocker, this should return a Hash with only the values that we care about.
xml_to_hash
ruby
facebook/IT-CPE
itchef/cookbooks/cpe_applocker/libraries/applocker_helpers.rb
https://github.com/facebook/IT-CPE/blob/master/itchef/cookbooks/cpe_applocker/libraries/applocker_helpers.rb
Apache-2.0