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 pagination_css_class
if request.xhr? and params[:from_page].present?
"frame_#{params[:from_page] > (params[:page] ? params[:page] : "1") ? 'left' : 'right'}"
else
"frame_center"
end
end | Figures out the CSS classname to apply to your pagination list for animations. | pagination_css_class | ruby | refinery/refinerycms | core/app/helpers/refinery/pagination_helper.rb | https://github.com/refinery/refinerycms/blob/master/core/app/helpers/refinery/pagination_helper.rb | MIT |
def site_bar_switch_link
link_to_if(admin?, t('.switch_to_your_website', site_bar_translate_locale_args),
refinery.root_path(site_bar_translate_locale_args),
'data-turbolinks' => false) do
link_to t('.switch_to_your_website_editor', site_bar_translate_locale_args),
Refinery::Core.backend_path, 'data-turbolinks' => false
end
end | Generates the link to determine where the site bar switch button returns to. | site_bar_switch_link | ruby | refinery/refinerycms | core/app/helpers/refinery/site_bar_helper.rb | https://github.com/refinery/refinerycms/blob/master/core/app/helpers/refinery/site_bar_helper.rb | MIT |
def refinery_help_tag(title='Tip')
title = title.html_safe? ? title : h(title)
action_icon(:info, '#', title, {tooltip: title})
end | Returns <img class='help' tooltip='Your Input' src='refinery/icons/information.png' />
Remember to wrap your block with <span class='label_with_help'></span> if you're using a label next to the help tag. | refinery_help_tag | ruby | refinery/refinerycms | core/app/helpers/refinery/tag_helper.rb | https://github.com/refinery/refinerycms/blob/master/core/app/helpers/refinery/tag_helper.rb | MIT |
def refinery_icon_tag(filename, options = {})
Refinery.deprecate('Refinery::TagHelper.refinery_icon_tag', when: '5.1', replacement: 'Refinery::TagHelper.action_icon')
filename = "#{filename}.png" unless filename.split('.').many?
path = image_path "refinery/icons/#{filename}", skip_pipeline: true
image_tag path, {:width => 16, :height => 16}.merge(options)
end | This is just a quick wrapper to render an image tag that lives inside refinery/icons.
They are all 16x16 so this is the default but is able to be overriden with supplied options. | refinery_icon_tag | ruby | refinery/refinerycms | core/app/helpers/refinery/tag_helper.rb | https://github.com/refinery/refinerycms/blob/master/core/app/helpers/refinery/tag_helper.rb | MIT |
def action_icon_label(action, url, title, options={}, label = true)
options[:title] = title
options[:class].presence ? options[:class] << " #{action}_icon " : options[:class] = "#{action}_icon"
options[:class] << ' icon_label' if label
case action
when :preview
options[:target] = '_blank'
when :delete
options[:method] = :delete
when :reorder_done
options[:class] << ' hidden'
end
link_to(label && title || '', url, options)
end | See icons.scss for defined icons/classes | action_icon_label | ruby | refinery/refinerycms | core/app/helpers/refinery/tag_helper.rb | https://github.com/refinery/refinerycms/blob/master/core/app/helpers/refinery/tag_helper.rb | MIT |
def locale_text_icon(text)
content_tag(:span, class: 'fa-stack') do
content_tag(:i, '', class: 'fa fa-comment') << content_tag(:strong, text)
end
end | this stacks the text onto the locale icon (actually a comment balloon) | locale_text_icon | ruby | refinery/refinerycms | core/app/helpers/refinery/tag_helper.rb | https://github.com/refinery/refinerycms/blob/master/core/app/helpers/refinery/tag_helper.rb | MIT |
def t(key, options = {})
if (val = super) =~ /class.+?translation_missing/
val = val.to_s.gsub(/<span[^>]*>/, 'i18n: ').gsub('</span>', '').gsub(', ', '.')
end
val
end | Overrides Rails' core I18n.t() function to produce a more helpful error message.
The default one wreaks havoc with CSS and makes it hard to understand the problem. | t | ruby | refinery/refinerycms | core/app/helpers/refinery/translation_helper.rb | https://github.com/refinery/refinerycms/blob/master/core/app/helpers/refinery/translation_helper.rb | MIT |
def register_extension(const)
return if extension_registered?(const)
validate_extension!(const)
@@extensions << const
end | Register an extension with Refinery
Example:
Refinery.register_extension(Refinery::Core) | register_extension | ruby | refinery/refinerycms | core/lib/refinery.rb | https://github.com/refinery/refinerycms/blob/master/core/lib/refinery.rb | MIT |
def deprecate(what, options = {})
# Build a warning.
warning = "\n-- DEPRECATION WARNING --\nThe use of '#{what}' is deprecated"
warning << " and will be removed at version #{options[:when]}" if options[:when]
warning << "."
warning << "\nPlease use #{options[:replacement]} instead." if options[:replacement]
# See if we can trace where this happened
if (invoker = detect_invoker(options[:caller])).present?
warning << invoker
end
# Give stern talking to.
warn warning
end | Constructs a deprecation warning message and warns with Kernel#warn
Example:
Refinery.deprecate('foo') => "The use of 'foo' is deprecated"
An options parameter can be specified to construct a more detailed deprecation message
Options:
when - version that this deprecated feature will be removed
replacement - a replacement for what is being deprecated
caller - who called the deprecated feature
Example:
Refinery.deprecate('foo', :when => 'tomorrow', :replacement => 'bar') =>
"The use of 'foo' is deprecated and will be removed at version 2.0. Please use 'bar' instead." | deprecate | ruby | refinery/refinerycms | core/lib/refinery.rb | https://github.com/refinery/refinerycms/blob/master/core/lib/refinery.rb | MIT |
def root
@root ||= Pathname.new(File.expand_path('../../../', __FILE__))
end | Returns a Pathname to the root of the Refinery CMS project | root | ruby | refinery/refinerycms | core/lib/refinery.rb | https://github.com/refinery/refinerycms/blob/master/core/lib/refinery.rb | MIT |
def roots(extension_name = nil)
return @roots ||= self.extensions.map(&:root) if extension_name.nil?
extension_name.to_s.camelize.constantize.root
end | Returns an array of Pathnames pointing to the root directory of each extension that
has been registered with Refinery.
Example:
Refinery.roots => [#<Pathname:/Users/Reset/Code/refinerycms/core>, #<Pathname:/Users/Reset/Code/refinerycms/pages>]
An optional extension_name parameter can be specified to return just the Pathname for
the specified extension. This can be represented in Constant, Symbol, or String form.
Example:
Refinery.roots(Refinery::Core) => #<Pathname:/Users/Reset/Code/refinerycms/core>
Refinery.roots(:'refinery/core') => #<Pathname:/Users/Reset/Code/refinerycms/core>
Refinery.roots("refinery/core") => #<Pathname:/Users/Reset/Code/refinerycms/core> | roots | ruby | refinery/refinerycms | core/lib/refinery.rb | https://github.com/refinery/refinerycms/blob/master/core/lib/refinery.rb | MIT |
def route_for_model(klass, options = {})
options = {:plural => false, :admin => true}.merge options
klass = klass.constantize if klass.respond_to?(:constantize)
active_name = ::ActiveModel::Name.new(
klass, (Refinery if klass.module_parents.include?(Refinery))
)
if options[:admin]
# Most of the time this gets rid of 'refinery'
parts = active_name.to_s.underscore.split('/').reject do |name|
active_name.singular_route_key.exclude?(name)
end
# Get the singular resource_name from the url parts
resource_name = parts.pop
resource_name = resource_name.pluralize if options[:plural]
[parts.join("_"), "admin", resource_name, "path"].reject(&:blank?).join "_"
else
path = options[:plural] ? active_name.route_key : active_name.singular_route_key
[path, 'path'].join '_'
end
end | Returns string version of url helper path. We need this to temporarily support namespaces
like Refinery::Image and Refinery::Blog::Post
Example:
Refinery.route_for_model(Refinery::Image) => "admin_image_path"
Refinery.route_for_model(Refinery::Image, {:plural => true}) => "admin_images_path"
Refinery.route_for_model(Refinery::Blog::Post) => "blog_admin_post_path"
Refinery.route_for_model(Refinery::Blog::Post, {:plural => true}) => "blog_admin_posts_path"
Refinery.route_for_model(Refinery::Blog::Post, {:admin => false}) => "blog_post_path" | route_for_model | ruby | refinery/refinerycms | core/lib/refinery.rb | https://github.com/refinery/refinerycms/blob/master/core/lib/refinery.rb | MIT |
def included_extension_module?(base, extension_module)
if base.kind_of?(Class)
direct_superclass = base.superclass
base.ancestors.take_while { |ancestor| ancestor != direct_superclass}.include?(extension_module)
else
base < extension_module # can't do better than that for modules
end
end | plain Module#included? or Module#included_modules doesn't cut it here | included_extension_module? | ruby | refinery/refinerycms | core/lib/refinery.rb | https://github.com/refinery/refinerycms/blob/master/core/lib/refinery.rb | MIT |
def destination_path
@destination_path ||= Pathname.new(self.destination_root)
end | Helper method to quickly convert destination_root to a Pathname for easy file path manipulation | destination_path | ruby | refinery/refinerycms | core/lib/generators/refinery/cms/cms_generator.rb | https://github.com/refinery/refinerycms/blob/master/core/lib/generators/refinery/cms/cms_generator.rb | MIT |
def present(model)
@meta = presenter_for(model).new(model)
end | use a different model for the meta information. | present | ruby | refinery/refinerycms | core/lib/refinery/application_controller.rb | https://github.com/refinery/refinerycms/blob/master/core/lib/refinery/application_controller.rb | MIT |
def after_inclusion(&block)
if block && block.respond_to?(:call)
after_inclusion_procs << block
else
raise 'Anything added to be called after_inclusion must be callable (respond to #call).'
end
end | Specify a block of code to be run after the refinery inclusion step. See
Refinery::Core::Engine#refinery_inclusion for details regarding the Refinery
inclusion process.
Example:
module Refinery
module Images
class Engine < Rails::Engine
extend Refinery::Engine
engine_name :images
after_inclusion do
# perform something here
end
end
end
end | after_inclusion | ruby | refinery/refinerycms | core/lib/refinery/engine.rb | https://github.com/refinery/refinerycms/blob/master/core/lib/refinery/engine.rb | MIT |
def before_inclusion(&block)
if block && block.respond_to?(:call)
before_inclusion_procs << block
else
raise 'Anything added to be called before_inclusion must be callable (respond to #call).'
end
end | Specify a block of code to be run before the refinery inclusion step. See
Refinery::Core::Engine#refinery_inclusion for details regarding the Refinery
inclusion process.
Example:
module Refinery
module Images
class Engine < Rails::Engine
extend Refinery::Engine
engine_name :images
before_inclusion do
# perform something here
end
end
end
end | before_inclusion | ruby | refinery/refinerycms | core/lib/refinery/engine.rb | https://github.com/refinery/refinerycms/blob/master/core/lib/refinery/engine.rb | MIT |
def merge_rb
(destination_lines[0..-2] + source_lines[1..-2] + [destination_lines.last]).join "\n"
end | merge_rb is only used for merging routes.rb
Put destination lines first, so that extension namespaced routes precede the default extension route | merge_rb | ruby | refinery/refinerycms | core/lib/refinery/extension_generation.rb | https://github.com/refinery/refinerycms/blob/master/core/lib/refinery/extension_generation.rb | MIT |
def compatible_with?(item)
original_type == item.original_type
end | At present a MenuItem can only have children of the same type to avoid id
conflicts like a Blog::Post and a Page both having an id of 42 | compatible_with? | ruby | refinery/refinerycms | core/lib/refinery/menu_item.rb | https://github.com/refinery/refinerycms/blob/master/core/lib/refinery/menu_item.rb | MIT |
def title
::I18n.translate(['refinery', 'plugins', name, 'title'].join('.'))
end | Returns the internationalized version of the title | title | ruby | refinery/refinerycms | core/lib/refinery/plugin.rb | https://github.com/refinery/refinerycms/blob/master/core/lib/refinery/plugin.rb | MIT |
def description
::I18n.translate(['refinery', 'plugins', name, 'description'].join('.'))
end | Returns the internationalized version of the description | description | ruby | refinery/refinerycms | core/lib/refinery/plugin.rb | https://github.com/refinery/refinerycms/blob/master/core/lib/refinery/plugin.rb | MIT |
def highlighted?(params)
!!(params[:controller].try(:gsub, "admin/", "") =~ menu_match)
end | Used to highlight the current tab in the admin interface | highlighted? | ruby | refinery/refinerycms | core/lib/refinery/plugin.rb | https://github.com/refinery/refinerycms/blob/master/core/lib/refinery/plugin.rb | MIT |
def url
@url ||= build_url
if @url.is_a?(Hash)
{ only_path: true }.merge(@url)
elsif @url.respond_to?(:call)
@url.call
else
@url
end
end | Returns a hash that can be used to create a url that points to the administration part of the plugin. | url | ruby | refinery/refinerycms | core/lib/refinery/plugin.rb | https://github.com/refinery/refinerycms/blob/master/core/lib/refinery/plugin.rb | MIT |
def store_location?
store_location unless request.xhr? || from_dialog?
end | TODO: all store_location stuff should be in its own object..
Check whether it makes sense to return the user to the last page they
were at instead of the default e.g. refinery_admin_pages_path
right now we just want to snap back to index actions and definitely not to dialogues. | store_location? | ruby | refinery/refinerycms | core/lib/refinery/admin/base_controller.rb | https://github.com/refinery/refinerycms/blob/master/core/lib/refinery/admin/base_controller.rb | MIT |
def store_location
session[:return_to] = request.fullpath
end | Store the URI of the current request in the session.
We can return to this location by calling #redirect_back_or_default. | store_location | ruby | refinery/refinerycms | core/lib/refinery/admin/base_controller.rb | https://github.com/refinery/refinerycms/blob/master/core/lib/refinery/admin/base_controller.rb | MIT |
def redirect_back_or_default(default)
redirect_to(pop_stored_location || default)
end | Redirect to the URI stored by the most recent store_location call or
to the passed default. | redirect_back_or_default | ruby | refinery/refinerycms | core/lib/refinery/admin/base_controller.rb | https://github.com/refinery/refinerycms/blob/master/core/lib/refinery/admin/base_controller.rb | MIT |
def backend_path
[mounted_path.gsub(%r{/\z}, ''), backend_route].join("/")
end | See https://github.com/refinery/refinerycms/issues/2740 | backend_path | ruby | refinery/refinerycms | core/lib/refinery/core/configuration.rb | https://github.com/refinery/refinerycms/blob/master/core/lib/refinery/core/configuration.rb | MIT |
def refinery_inclusion!
before_inclusion_procs.each(&:call).tap do |c|
c.clear if Rails.application.config.cache_classes
end
Refinery.include_once(::ApplicationController, Refinery::ApplicationController)
::ApplicationController.send :helper, Refinery::Core::Engine.helpers
after_inclusion_procs.each(&:call).tap do |c|
c.clear if Rails.application.config.cache_classes
end
# Register all decorators from app/decorators/ and registered plugins' paths.
Decorators.register! Rails.root, Refinery::Plugins.registered.pathnames
end | Performs the Refinery inclusion process which extends the currently loaded Rails
applications with Refinery's controllers and helpers. The process is wrapped by
a before_inclusion and after_inclusion step that calls procs registered by the
Refinery::Engine#before_inclusion and Refinery::Engine#after_inclusion class methods | refinery_inclusion! | ruby | refinery/refinerycms | core/lib/refinery/core/engine.rb | https://github.com/refinery/refinerycms/blob/master/core/lib/refinery/core/engine.rb | MIT |
def capture(stream=STDOUT, &block)
old_stdout = stream.clone
pipe_r, pipe_w = IO.pipe
pipe_r.sync = true
output = ""
reader = Thread.new do
begin
loop do
output << pipe_r.readpartial(1024)
end
rescue EOFError
end
end
stream.reopen(pipe_w)
yield
ensure
stream.reopen(old_stdout)
pipe_w.close
reader.join
pipe_r.close
return output
end | From episode 029 of Ruby Tapas by Avdi
https://rubytapas.dpdcart.com/subscriber/post?id=88 | capture | ruby | refinery/refinerycms | core/spec/lib/refinery/cli_spec.rb | https://github.com/refinery/refinerycms/blob/master/core/spec/lib/refinery/cli_spec.rb | MIT |
def dragonfly_mime_types
config.dragonfly_mime_types || Refinery::Dragonfly.mime_types
end | define one or more new mimetypes
dragonfly_mimetypes = [
{ext: 'egg', mimetype: 'fried/egg'},
{ext: 'avo', mimetype: 'smashed/avo'}
] | dragonfly_mime_types | ruby | refinery/refinerycms | dragonfly/lib/refinery/dragonfly/extension_configuration.rb | https://github.com/refinery/refinerycms/blob/master/dragonfly/lib/refinery/dragonfly/extension_configuration.rb | MIT |
def insert
self.new if @image.nil?
@url_override = refinery.admin_images_path(request.query_parameters.merge(insert: true))
if params[:conditions].present?
extra_condition = params[:conditions].split(',')
extra_condition[1] = true if extra_condition[1] == "true"
extra_condition[1] = false if extra_condition[1] == "false"
extra_condition[1] = nil if extra_condition[1] == "nil"
end
find_all_images(({extra_condition[0] => extra_condition[1]} if extra_condition.present?))
search_all_images if searching?
paginate_images
render 'insert'
end | This renders the image insert dialog | insert | ruby | refinery/refinerycms | images/app/controllers/refinery/admin/images_controller.rb | https://github.com/refinery/refinerycms/blob/master/images/app/controllers/refinery/admin/images_controller.rb | MIT |
def per_page(dialog = false, has_size_options = false)
if dialog
if has_size_options
Images.pages_per_dialog_that_have_size_options
else
Images.pages_per_dialog
end
else
Images.pages_per_admin_index
end
end | How many images per page should be displayed? | per_page | ruby | refinery/refinerycms | images/app/models/refinery/image.rb | https://github.com/refinery/refinerycms/blob/master/images/app/models/refinery/image.rb | MIT |
def thumbnail(options = {})
options = { geometry: nil, strip: false }.merge(options)
geometry = convert_to_geometry(options[:geometry])
thumbnail = image
thumbnail = thumbnail.thumb(geometry) if geometry
thumbnail = thumbnail.strip if options[:strip]
thumbnail
end | Get a thumbnail job object given a geometry and whether to strip image profiles and comments. | thumbnail | ruby | refinery/refinerycms | images/app/models/refinery/image.rb | https://github.com/refinery/refinerycms/blob/master/images/app/models/refinery/image.rb | MIT |
def thumbnail_dimensions(geometry)
dimensions = ThumbnailDimensions.new(geometry, image.width, image.height)
{ width: dimensions.width, height: dimensions.height }
end | Intelligently works out dimensions for a thumbnail of this image based on the Dragonfly geometry string. | thumbnail_dimensions | ruby | refinery/refinerycms | images/app/models/refinery/image.rb | https://github.com/refinery/refinerycms/blob/master/images/app/models/refinery/image.rb | MIT |
def title
image_title.presence || CGI::unescape(image_name.to_s).gsub(/\.\w+$/, '').titleize
end | Returns a titleized version of the filename
my_file.jpg returns My File | title | ruby | refinery/refinerycms | images/app/models/refinery/image.rb | https://github.com/refinery/refinerycms/blob/master/images/app/models/refinery/image.rb | MIT |
def home
if page.link_url.present? && page.link_url != "/"
redirect_to page.link_url, status: 301 and return
end
render_with_templates?
end | This action is usually accessed with the root path, normally '/' | home | ruby | refinery/refinerycms | pages/app/controllers/refinery/pages_controller.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/controllers/refinery/pages_controller.rb | MIT |
def show
if should_skip_to_first_child?
redirect_to refinery.url_for(first_live_child.url), status: 301 and return
elsif page.link_url.present?
redirect_to page.link_url, status: 301 and return
elsif should_redirect_to_friendly_url?
redirect_to refinery.url_for(page.url), status: 301 and return
end
render_with_templates?
end | This action can be accessed normally, or as nested pages.
Assuming a page named "mission" that is a child of "about",
you can access the pages with the following URLs:
GET /pages/about
GET /about
GET /pages/mission
GET /about/mission | show | ruby | refinery/refinerycms | pages/app/controllers/refinery/pages_controller.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/controllers/refinery/pages_controller.rb | MIT |
def mobility!
return super unless action_name.to_s == 'index'
# Always display the tree of pages from the default frontend locale.
if Refinery::I18n.built_in_locales.keys.map(&:to_s).include?(params[:switch_locale])
Mobility.locale = params[:switch_locale].try(:to_sym)
else
Mobility.locale = Refinery::I18n.default_frontend_locale
end
end | We can safely assume ::Refinery::I18n is defined because this method only gets
Invoked when the before_action from the plugin is run. | mobility! | ruby | refinery/refinerycms | pages/app/controllers/refinery/admin/pages_controller.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/controllers/refinery/admin/pages_controller.rb | MIT |
def page_meta_information(page)
meta_information = ActiveSupport::SafeBuffer.new
meta_information << content_tag(:span, :class => 'label') do
::I18n.t('hidden', :scope => 'refinery.admin.pages.page')
end unless page.show_in_menu?
meta_information << content_tag(:span, :class => 'label') do
::I18n.t('skip_to_first_child', :scope => 'refinery.admin.pages.page')
end if page.skip_to_first_child?
meta_information << content_tag(:span, :class => 'label') do
::I18n.t('redirected', :scope => 'refinery.admin.pages.page')
end if page.link_url?
meta_information << content_tag(:span, :class => 'label notice') do
::I18n.t('draft', :scope => 'refinery.admin.pages.page')
end if page.draft?
meta_information
end | In the admin area we use a slightly different title
to inform the which pages are draft or hidden pages | page_meta_information | ruby | refinery/refinerycms | pages/app/helpers/refinery/admin/pages_helper.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/helpers/refinery/admin/pages_helper.rb | MIT |
def render_content_page(page, options = {})
content_page_presenter = Refinery::Pages::ContentPagePresenter.new(page, page_title)
render_content_presenter(content_page_presenter, options)
end | Build the html for a Refinery CMS page object by creating a ContentPagePresenter. This is a
specialised type of ContentPresenter, so the object is then passed to render_content_presenter
to get its html. The options are passed to that method, so see render_content_presenter for
more details. | render_content_page | ruby | refinery/refinerycms | pages/app/helpers/refinery/pages/content_pages_helper.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/helpers/refinery/pages/content_pages_helper.rb | MIT |
def render_content_presenter(content_page, options = {})
content_page.hide_sections(options[:hide_sections]) if options[:hide_sections]
content_page.fetch_template_overrides { |section_id| content_for(section_id)}
content_page.to_html(options[:can_use_fallback])
end | Pass the options into a ContentPresenter object and return its html. For more
details see Refinery::Pages::ContentPresenter (and its subclasses).
This method also checks for template overrides. Any template rendered by the
current action may specify content_for a section using the section's id. For this
reason, sections should not have an ID which you would normally be using for content_for,
so avoid common layout names such as :header, :footer, etc. | render_content_presenter | ruby | refinery/refinerycms | pages/app/helpers/refinery/pages/content_pages_helper.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/helpers/refinery/pages/content_pages_helper.rb | MIT |
def should_generate_new_friendly_id?
title_changed? || custom_slug_changed?
end | If title changes tell friendly_id to regenerate slug when saving record | should_generate_new_friendly_id? | ruby | refinery/refinerycms | pages/app/models/refinery/page.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/models/refinery/page.rb | MIT |
def live
where(:draft => false)
end | Live pages are 'allowed' to be shown in the frontend of your website.
By default, this is all pages that are not set as 'draft'. | live | ruby | refinery/refinerycms | pages/app/models/refinery/page.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/models/refinery/page.rb | MIT |
def find_by_path_or_id(path, id)
Pages::Finder.by_path_or_id(path, id)
end | Helps to resolve the situation where you have a path and an id
and if the path is unfriendly then a different finder method is required
than find_by_path. | find_by_path_or_id | ruby | refinery/refinerycms | pages/app/models/refinery/page.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/models/refinery/page.rb | MIT |
def find_by_path_or_id!(path, id)
page = find_by_path_or_id(path, id)
raise ::ActiveRecord::RecordNotFound unless page
page
end | Helps to resolve the situation where you have a path and an id
and if the path is unfriendly then a different finder method is required
than find_by_path.
raise ActiveRecord::RecordNotFound if not found. | find_by_path_or_id! | ruby | refinery/refinerycms | pages/app/models/refinery/page.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/models/refinery/page.rb | MIT |
def by_slug(slug, conditions = {})
Pages::Finder.by_slug(slug, conditions)
end | Finds pages by their slug. This method is necessary because pages
are translated which means the slug attribute does not exist on the
pages table thus requiring us to find the attribute on the translations table
and then join to the pages table again to return the associated record. | by_slug | ruby | refinery/refinerycms | pages/app/models/refinery/page.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/models/refinery/page.rb | MIT |
def in_menu
where(show_in_menu: true).with_mobility
end | Shows all pages with :show_in_menu set to true, but it also
rejects any page that has not been translated to the current locale.
This works using a query against the translated content first and then
using all of the page_ids we further filter against this model's table. | in_menu | ruby | refinery/refinerycms | pages/app/models/refinery/page.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/models/refinery/page.rb | MIT |
def fast_menu
live.in_menu.order(arel_table[:lft]).includes(:parent, :translations)
end | An optimised scope containing only live pages ordered for display in a menu. | fast_menu | ruby | refinery/refinerycms | pages/app/models/refinery/page.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/models/refinery/page.rb | MIT |
def per_page(dialog = false)
dialog ? Pages.pages_per_dialog : Pages.pages_per_admin_index
end | Returns how many pages per page should there be when paginating pages | per_page | ruby | refinery/refinerycms | pages/app/models/refinery/page.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/models/refinery/page.rb | MIT |
def canonical
Mobility.with_locale(::Refinery::I18n.current_frontend_locale) { url }
end | The canonical page for this particular page.
Consists of:
* The current locale's translated slug | canonical | ruby | refinery/refinerycms | pages/app/models/refinery/page.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/models/refinery/page.rb | MIT |
def canonical_slug
Mobility.with_locale(::Refinery::I18n.current_frontend_locale) { slug }
end | The canonical slug for this particular page.
This is the slug for the current frontend locale. | canonical_slug | ruby | refinery/refinerycms | pages/app/models/refinery/page.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/models/refinery/page.rb | MIT |
def custom_slug_or_title
(Refinery::Pages.use_custom_slugs && custom_slug.presence) ||
menu_title.presence || title.presence
end | Returns in cascading order: custom_slug or menu_title or title depending on
which attribute is first found to be present for this page. | custom_slug_or_title | ruby | refinery/refinerycms | pages/app/models/refinery/page.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/models/refinery/page.rb | MIT |
def deletable?
deletable && link_url.blank? && menu_match.blank?
end | Am I allowed to delete this page?
If a link_url is set we don't want to break the link so we don't allow them to delete
If deletable is set to false then we don't allow this page to be deleted. These are often Refinery system pages | deletable? | ruby | refinery/refinerycms | pages/app/models/refinery/page.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/models/refinery/page.rb | MIT |
def reposition_parts!
reload.parts.each_with_index do |part, index|
part.update_columns position: index
end
end | Repositions the child page_parts that belong to this page.
This ensures that they are in the correct 0,1,2,3,4... etc order. | reposition_parts! | ruby | refinery/refinerycms | pages/app/models/refinery/page.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/models/refinery/page.rb | MIT |
def destroy
return super if deletable?
puts_destroy_help
false
end | Before destroying a page we check to see if it's a deletable page or not
Refinery system pages are not deletable. | destroy | ruby | refinery/refinerycms | pages/app/models/refinery/page.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/models/refinery/page.rb | MIT |
def destroy!
self.update(:menu_match => nil, :link_url => nil, :deletable => true)
self.destroy
end | If you want to destroy a page that is set to be not deletable this is the way to do it. | destroy! | ruby | refinery/refinerycms | pages/app/models/refinery/page.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/models/refinery/page.rb | MIT |
def path(path_separator: ' - ', ancestors_first: true)
return title if root?
chain = ancestors_first ? self_and_ancestors : self_and_ancestors.reverse
chain.map(&:title).join(path_separator)
end | Returns the full path to this page.
This automatically prints out this page title and all parent page titles.
The result is joined by the path_separator argument. | path | ruby | refinery/refinerycms | pages/app/models/refinery/page.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/models/refinery/page.rb | MIT |
def nested_path
['', nested_url].join('/')
end | Returns the string version of nested_url, i.e., the path that should be
generated by the router | nested_path | ruby | refinery/refinerycms | pages/app/models/refinery/page.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/models/refinery/page.rb | MIT |
def in_menu?
live? && show_in_menu?
end | Return true if this page can be shown in the navigation.
If it's a draft or is set to not show in the menu it will return false. | in_menu? | ruby | refinery/refinerycms | pages/app/models/refinery/page.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/models/refinery/page.rb | MIT |
def part_with_slug(part_slug)
# self.parts is usually already eager loaded so we can now just grab
# the first element matching the title we specified.
self.parts.detect do |part|
part.slug_matches?(part_slug)
end
end | Accessor method to get a page part object from a page.
Example:
::Refinery::Page.first.part_with_slug(:body)
Will return the Refinery::PagePart object with that slug using the first page. | part_with_slug | ruby | refinery/refinerycms | pages/app/models/refinery/page.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/models/refinery/page.rb | MIT |
def descendant_item_selected?(item)
item.has_children? && item.descendants.any?(&method(:selected_item?))
end | Determines whether any item underneath the supplied item is the current item according to rails.
Just calls selected_item? for each descendant of the supplied item
unless it first quickly determines that there are no descendants. | descendant_item_selected? | ruby | refinery/refinerycms | pages/app/presenters/refinery/pages/menu_presenter.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/presenters/refinery/pages/menu_presenter.rb | MIT |
def selected_item?(item)
# Ensure we match the path without the locale, if present.
path = match_locale_for(encoded_path)
# First try to match against a "menu match" value, if available.
return true if menu_match_is_available?(item, path)
# Find the first url that is a string.
url = find_url_for(item)
# Now use all possible vectors to try to find a valid match
[path, CGI.unescape(path)].include?(url) || path == "/#{item.original_id}"
end | Determine whether the supplied item is the currently open item according to Refinery. | selected_item? | ruby | refinery/refinerycms | pages/app/presenters/refinery/pages/menu_presenter.rb | https://github.com/refinery/refinerycms/blob/master/pages/app/presenters/refinery/pages/menu_presenter.rb | MIT |
def add_route_parts_as_reserved_words
ActiveSupport.on_load(:active_record) do
# do not add routes with :allow_slug => true
included_routes = Rails.application.routes.named_routes.to_a.reject{ |name, route| route.defaults[:allow_slug] }
route_paths = included_routes.map { |name, route| route.path.spec }
route_paths.reject! { |path| path.to_s =~ %r{^/(rails|refinery)}}
Refinery::Pages.friendly_id_reserved_words |= route_paths.map { |path|
path.to_s.gsub(%r{^/}, '').to_s.split('(').first.to_s.split(':').first.to_s.split('/')
}.flatten.reject { |w| w =~ %r{_|\.} }.uniq
end
end | Add any parts of routes as reserved words. | add_route_parts_as_reserved_words | ruby | refinery/refinerycms | pages/lib/refinery/pages/engine.rb | https://github.com/refinery/refinerycms/blob/master/pages/lib/refinery/pages/engine.rb | MIT |
def title
resource_title.presence || CGI.unescape(file_name.to_s).gsub(/\.\w+$/, '').titleize
end | Returns a titleized version of the filename
my_file.pdf returns My File | title | ruby | refinery/refinerycms | resources/app/models/refinery/resource.rb | https://github.com/refinery/refinerycms/blob/master/resources/app/models/refinery/resource.rb | MIT |
def per_page(dialog = false)
dialog ? Resources.pages_per_dialog : Resources.pages_per_admin_index
end | How many resources per page should be displayed? | per_page | ruby | refinery/refinerycms | resources/app/models/refinery/resource.rb | https://github.com/refinery/refinerycms/blob/master/resources/app/models/refinery/resource.rb | MIT |
def load_factories
Refinery.extensions.each do |extension_const|
if extension_const.respond_to?(:factory_paths)
extension_const.send(:factory_paths).each do |path|
FactoryBot.definition_file_paths << path
end
end
end
FactoryBot.find_definitions
end | Load the factories of all currently loaded extensions | load_factories | ruby | refinery/refinerycms | testing/lib/refinery/testing.rb | https://github.com/refinery/refinerycms/blob/master/testing/lib/refinery/testing.rb | MIT |
def load_dummy_tasks(app_root)
@target_extension_path = Pathname.new(app_root.to_s)
load 'refinery/tasks/testing.rake'
end | Loads Rake tasks to assist with manipulating dummy applications for testing extensions. Takes
a string representing the path to your application or extension.
This function should be used in the Rakefile of your application or extension
Example:
Refinery::Testing::Railtie.load_dummy_tasks(File.dirname(__FILE__))
Refinery::Testing::Railtie.load_dummy_tasks('/users/reset/code/mynew_app') | load_dummy_tasks | ruby | refinery/refinerycms | testing/lib/refinery/testing/railtie.rb | https://github.com/refinery/refinerycms/blob/master/testing/lib/refinery/testing/railtie.rb | MIT |
def initialize(model_class)
@model_class = model_class
@records = []
end | Use for_model instead of instatiating a record directly. | initialize | ruby | ryanb/populator | lib/populator/factory.rb | https://github.com/ryanb/populator/blob/master/lib/populator/factory.rb | MIT |
def populate(amount, options = {}, &block)
self.class.remember_depth do
build_records(Populator.interpret_value(amount), options[:per_query] || DEFAULT_RECORDS_PER_QUERY, &block)
end
end | Entry method for building records. Delegates to build_records after remember_depth. | populate | ruby | ryanb/populator | lib/populator/factory.rb | https://github.com/ryanb/populator/blob/master/lib/populator/factory.rb | MIT |
def save_records
unless @records.empty?
@model_class.connection.populate(@model_class.quoted_table_name, columns_sql, rows_sql_arr, "#{@model_class.name} Populate")
@last_id_in_database = @records.last.id
@records.clear
end
end | Saves the records to the database by calling populate on the current database adapter. | save_records | ruby | ryanb/populator | lib/populator/factory.rb | https://github.com/ryanb/populator/blob/master/lib/populator/factory.rb | MIT |
def value_in_range(range)
case range.first
when Integer then number_in_range(range)
when Time then time_in_range(range)
when Date then date_in_range(range)
else range.to_a[rand(range.to_a.size)]
end
end | Pick a random value out of a given range. | value_in_range | ruby | ryanb/populator | lib/populator/random.rb | https://github.com/ryanb/populator/blob/master/lib/populator/random.rb | MIT |
def words(total)
(1..interpret_value(total)).map { WORDS[rand(WORDS.size)] }.join(' ')
end | Generate a given number of words. If a range is passed, it will generate
a random number of words within that range. | words | ruby | ryanb/populator | lib/populator/random.rb | https://github.com/ryanb/populator/blob/master/lib/populator/random.rb | MIT |
def sentences(total)
(1..interpret_value(total)).map do
words(5..20).capitalize
end.join('. ')
end | Generate a given number of sentences. If a range is passed, it will generate
a random number of sentences within that range. | sentences | ruby | ryanb/populator | lib/populator/random.rb | https://github.com/ryanb/populator/blob/master/lib/populator/random.rb | MIT |
def paragraphs(total)
(1..interpret_value(total)).map do
sentences(3..8).capitalize
end.join("\n\n")
end | Generate a given number of paragraphs. If a range is passed, it will generate
a random number of paragraphs within that range. | paragraphs | ruby | ryanb/populator | lib/populator/random.rb | https://github.com/ryanb/populator/blob/master/lib/populator/random.rb | MIT |
def interpret_value(value)
case value
when Array then value[rand(value.size)]
when Range then value_in_range(value)
else value
end
end | If an array or range is passed, a random value will be selected to match.
All other values are simply returned. | interpret_value | ruby | ryanb/populator | lib/populator/random.rb | https://github.com/ryanb/populator/blob/master/lib/populator/random.rb | MIT |
def initialize(model_class, id)
@attributes = { model_class.primary_key.to_sym => id }
@columns = model_class.column_names
@columns.each do |column|
case column
when 'created_at', 'updated_at'
@attributes[column.to_sym] = Time.now
when 'created_on', 'updated_on'
@attributes[column.to_sym] = Date.today
when model_class.inheritance_column
@attributes[column.to_sym] = model_class.to_s
end
end
end | Creates a new instance of Record. Some attributes are set by default:
* <tt>id</tt> - defaults to id passed
* <tt>created_at</tt> - defaults to current time
* <tt>updated_at</tt> - defaults to current time
* <tt>created_on</tt> - defaults to current date
* <tt>updated_on</tt> - defaults to current date
* <tt>type</tt> - defaults to class name (for STI) | initialize | ruby | ryanb/populator | lib/populator/record.rb | https://github.com/ryanb/populator/blob/master/lib/populator/record.rb | MIT |
def attribute_values
@columns.map do |column|
@attributes[column.to_sym]
end
end | Return values for all columns inside an array. | attribute_values | ruby | ryanb/populator | lib/populator/record.rb | https://github.com/ryanb/populator/blob/master/lib/populator/record.rb | MIT |
def execute_batch(sql, name = nil)
raise NotImplementedError, "execute_batch is an abstract method"
end | Executes multiple SQL statements in one query when joined with ";" | execute_batch | ruby | ryanb/populator | lib/populator/adapters/abstract.rb | https://github.com/ryanb/populator/blob/master/lib/populator/adapters/abstract.rb | MIT |
def populate(table, columns, rows, name = nil)
rows.each do |row|
sql = "INSERT INTO #{table} #{columns} VALUES #{row}"
log(sql, name) do
@connection.exec(sql)
end
end
end | Executes SQL statements one at a time. | populate | ruby | ryanb/populator | lib/populator/adapters/oracle.rb | https://github.com/ryanb/populator/blob/master/lib/populator/adapters/oracle.rb | MIT |
def execute_batch(sql, name = nil)
log(sql, name) do
@connection.transaction { |db| db.execute_batch(sql) }
end
end | Executes multiple SQL statements in one query when joined with ";" | execute_batch | ruby | ryanb/populator | lib/populator/adapters/sqlite.rb | https://github.com/ryanb/populator/blob/master/lib/populator/adapters/sqlite.rb | MIT |
def initialize(target_width = DEFAULT_TARGET_WIDTH)
if target_width.is_a?(String)
@columns, @rows = target_width.split('x').map(&:to_f)
else
@columns = target_width.to_f
@rows = target_width.to_f * 0.75
end
@columns.freeze
@rows.freeze
@has_left_labels = false
@center_labels_over_point = true
initialize_graph_scale
initialize_attributes
initialize_store
self.theme = Themes::KEYNOTE
end | If one numerical argument is given, the graph is drawn at 4/3 ratio
according to the given width (+800+ results in 800x600, +400+ gives 400x300,
etc.).
Or, send a geometry string for other ratios ( +'800x400'+, +'400x225'+).
@param target_width [Numeric, String] The graph image width.
@rbs target_width: (String | Float | Integer)
@rbs return: void | initialize | ruby | topfunky/gruff | lib/gruff/base.rb | https://github.com/topfunky/gruff/blob/master/lib/gruff/base.rb | MIT |
def initialize_attributes
@marker_count = nil
@maximum_value = @minimum_value = nil
@labels = {}
@sort = false
@sorted_drawing = false
@title = nil
@title_font = Gruff::Font.new(size: 36.0, bold: true)
@marker_font = Gruff::Font.new(size: 21.0)
@legend_font = Gruff::Font.new(size: 20.0)
@no_data_font = Gruff::Font.new(size: 80.0)
@label_margin = LABEL_MARGIN
@top_margin = @bottom_margin = @left_margin = @right_margin = DEFAULT_MARGIN
@legend_margin = LEGEND_MARGIN
@title_margin = TITLE_MARGIN
@legend_box_size = 20.0
@no_data_message = 'No Data'
@hide_line_markers = @hide_legend = @hide_title = @hide_line_numbers = @legend_at_bottom = false
@label_max_size = 0
@label_truncation_style = :absolute
@label_rotation = 0
@x_axis_increment = nil
@x_axis_label = @y_axis_label = nil
@y_axis_increment = nil
@x_axis_label_format = nil
@y_axis_label_format = nil
end | Initialize instance variable of attributes
Subclasses can override this, call super, then set values separately.
This makes it possible to set defaults in a subclass but still allow
developers to change this values in their program. | initialize_attributes | ruby | topfunky/gruff | lib/gruff/base.rb | https://github.com/topfunky/gruff/blob/master/lib/gruff/base.rb | MIT |
def add_color(colorname)
@colors << colorname
end | Add a color to the list of available colors for lines.
@param colorname [String] The color.
@rbs colorname: String
@example
add_color('#c0e9d3') | add_color | ruby | topfunky/gruff | lib/gruff/base.rb | https://github.com/topfunky/gruff/blob/master/lib/gruff/base.rb | MIT |
def replace_colors(color_list = [])
@colors = color_list
end | Replace the entire color list with a new array of colors. Also
aliased as the {#colors=} setter method.
If you specify fewer colors than the number of datasets you intend
to draw, it will cycle through the array, reusing colors as needed.
Note that (as with the {#theme=} method), you should set up your color
list before you send your data (via the {#data} method). Calls to the
{#data} method made prior to this call will use whatever color scheme
was in place at the time data was called.
@param color_list [Array] The array of colors.
@rbs color_list: Array[String]
@example
replace_colors ['#cc99cc', '#d9e043', '#34d8a2'] | replace_colors | ruby | topfunky/gruff | lib/gruff/base.rb | https://github.com/topfunky/gruff/blob/master/lib/gruff/base.rb | MIT |
def data(name, data_points = [], color = nil)
store.add(name, data_points, color)
end | Input the data in the graph.
Parameters are an array where the first element is the name of the dataset
and the value is an array of values to plot.
Can be called multiple times with different datasets for a multi-valued
graph.
If the color argument is nil, the next color from the default theme will
be used.
@param name [String, Symbol] The name of the dataset.
@rbs name: (String | Symbol)
@param data_points [Array] The array of dataset.
@rbs data_points: Array[Float | Integer] | nil
@param color [String] The color for drawing graph of dataset.
@rbs color: String
@note
If you want to use a preset theme, you must set it before calling {#data}.
@example
data("Bart S.", [95, 45, 78, 89, 88, 76], '#ffcc00') | data | ruby | topfunky/gruff | lib/gruff/base.rb | https://github.com/topfunky/gruff/blob/master/lib/gruff/base.rb | MIT |
def minimum_value
min = [0.0, store.min.to_f].min
(@minimum_value || min).to_f
end | You can manually set a minimum value instead of having the values
guessed for you.
Set it after you have given all your data to the graph object.
@return [Float] The minimum value.
@rbs return: Float | minimum_value | ruby | topfunky/gruff | lib/gruff/base.rb | https://github.com/topfunky/gruff/blob/master/lib/gruff/base.rb | MIT |
def maximum_value
(@maximum_value || store.max).to_f
end | You can manually set a maximum value, such as a percentage-based graph
that always goes to 100.
If you use this, you must set it after you have given all your data to
the graph object.
@return [Float] The maximum value.
@rbs return: Float | maximum_value | ruby | topfunky/gruff | lib/gruff/base.rb | https://github.com/topfunky/gruff/blob/master/lib/gruff/base.rb | MIT |
def to_image(format = 'PNG')
@to_image ||= begin
draw
renderer.finish
image = renderer.image
image.format = format
image
end
end | Return a rendered graph image.
This can use RMagick's methods to adjust the image before saving.
@param format [String] The output image format.
@rbs format: String
@return [Magick::Image] The rendered image.
TODO: RBS signature
@example
g = Gruff::Line.new
g.data :Jimmy, [25, 36, 86, 39, 25, 31, 79, 88]
g.data :Charles, [80, 54, 67, 54, 68, 70, 90, 95]
image = g.to_image
image = image.resize(400, 300).quantize(128, Magick::RGBColorspace)
image.write('test.png') | to_image | ruby | topfunky/gruff | lib/gruff/base.rb | https://github.com/topfunky/gruff/blob/master/lib/gruff/base.rb | MIT |
def to_blob(format = 'PNG')
warn '#to_blob is deprecated. Please use `to_image.to_blob` instead'
to_image.format = format
to_image.to_blob
end | Return the graph as a rendered binary blob.
@param format [String] The image format of binary blob.
@rbs format: String
@return [String] The binary string.
@rbs return: String
@deprecated Please use +to_image.to_blob+ instead. | to_blob | ruby | topfunky/gruff | lib/gruff/base.rb | https://github.com/topfunky/gruff/blob/master/lib/gruff/base.rb | MIT |
def setup_data
if @y_axis_increment && !@hide_line_markers
self.maximum_value = [@y_axis_increment, maximum_value, (maximum_value / @y_axis_increment).round * @y_axis_increment].max
self.minimum_value = [minimum_value, (minimum_value / @y_axis_increment).round * @y_axis_increment].min
end
sort_data if @sort # Sort data with avg largest values set first (for display)
end | Perform data manipulation before calculating chart measurements | setup_data | ruby | topfunky/gruff | lib/gruff/base.rb | https://github.com/topfunky/gruff/blob/master/lib/gruff/base.rb | MIT |
def setup_drawing
calculate_spread
calculate_increment
set_colors
normalize
setup_graph_measurements
sort_norm_data if @sorted_drawing # Sort norm_data with avg largest values set first (for display)
end | Calculates size of drawable area and generates normalized data.
* line markers
* legend
* title | setup_drawing | ruby | topfunky/gruff | lib/gruff/base.rb | https://github.com/topfunky/gruff/blob/master/lib/gruff/base.rb | MIT |
def normalize
store.normalize(minimum: minimum_value, spread: @spread)
end | Make copy of data with values scaled between 0-100
@rbs return: Array[Gruff::Store::BasicData | Gruff::Store::XYData | Gruff::Store::XYPointsizeData] | normalize | ruby | topfunky/gruff | lib/gruff/base.rb | https://github.com/topfunky/gruff/blob/master/lib/gruff/base.rb | MIT |
def setup_graph_measurements
@graph_right = setup_right_margin
@graph_left = setup_left_margin
@graph_top = setup_top_margin
@graph_bottom = setup_bottom_margin
@graph_width = @graph_right - @graph_left
@graph_height = @graph_bottom - @graph_top
end | #
Calculates size of drawable area, general font dimensions, etc. | setup_graph_measurements | ruby | topfunky/gruff | lib/gruff/base.rb | https://github.com/topfunky/gruff/blob/master/lib/gruff/base.rb | MIT |
def draw_axis_labels
if @x_axis_label
# X Axis
# Centered vertically and horizontally by setting the
# height to 1.0 and the width to the width of the graph.
x_axis_label_y_coordinate = @graph_bottom + (@label_margin * 2) + labels_caps_height
text_renderer = Gruff::Renderer::Text.new(renderer, @x_axis_label, font: @marker_font)
text_renderer.add_to_render_queue(@raw_columns, 1.0, 0.0, x_axis_label_y_coordinate)
end
if @y_axis_label
# Y Axis, rotated vertically
text_renderer = Gruff::Renderer::Text.new(renderer, @y_axis_label, font: @marker_font, rotation: -90)
text_renderer.add_to_render_queue(1.0, @raw_rows, @left_margin + (marker_caps_height / 2.0), 0.0, Magick::CenterGravity)
end
end | Draw the optional labels for the x axis and y axis. | draw_axis_labels | ruby | topfunky/gruff | lib/gruff/base.rb | https://github.com/topfunky/gruff/blob/master/lib/gruff/base.rb | MIT |
def draw_line_markers
return if @hide_line_markers
increment_scaled = (@graph_height / (@spread / @increment)).to_f
# Draw horizontal line markers and annotate with numbers
(0..marker_count).each do |index|
y = @graph_top + @graph_height - (index * increment_scaled)
draw_marker_horizontal_line(y)
unless @hide_line_numbers
marker_label = (BigDecimal(index.to_s) * BigDecimal(@increment.to_s)) + BigDecimal(minimum_value.to_s)
label = y_axis_label(marker_label, @increment)
text_renderer = Gruff::Renderer::Text.new(renderer, label, font: @marker_font)
text_renderer.add_to_render_queue(@graph_left - @label_margin, 1.0, 0.0, y, Magick::EastGravity)
end
end
end | Draws horizontal background lines and labels | draw_line_markers | ruby | topfunky/gruff | lib/gruff/base.rb | https://github.com/topfunky/gruff/blob/master/lib/gruff/base.rb | MIT |
def center(size)
(@raw_columns - size) / 2.0
end | Return a calculation of center
@rbs size: Float | Integer
@rbs return: Float | center | ruby | topfunky/gruff | lib/gruff/base.rb | https://github.com/topfunky/gruff/blob/master/lib/gruff/base.rb | MIT |
def draw_legend
return if @hide_legend
legend_labels = store.data.map(&:label)
legend_square_width = @legend_box_size # small square with color of this item
legend_label_lines = calculate_legend_label_widths_for_each_line(legend_labels, legend_square_width)
line_height = [legend_caps_height, legend_square_width].max + @legend_margin
current_y_offset = begin
if @legend_at_bottom
@graph_bottom + @legend_margin + labels_caps_height + @label_margin + (@x_axis_label ? (@label_margin * 2) + marker_caps_height : 0)
else
hide_title? ? @top_margin + @title_margin : @top_margin + @title_margin + title_caps_height
end
end
index = 0
legend_label_lines.each do |(legend_labels_width, legend_labels_line)|
current_x_offset = center(legend_labels_width)
legend_labels_line.each do |legend_label|
unless legend_label.empty?
legend_label_width = calculate_width(@legend_font, legend_label)
# Draw label
text_renderer = Gruff::Renderer::Text.new(renderer, legend_label, font: @legend_font)
text_renderer.add_to_render_queue(legend_label_width,
legend_square_width,
current_x_offset + (legend_square_width * 1.7),
current_y_offset,
Magick::CenterGravity)
# Now draw box with color of this dataset
rect_renderer = Gruff::Renderer::Rectangle.new(renderer, color: store.data[index].color)
rect_renderer.render(current_x_offset,
current_y_offset,
current_x_offset + legend_square_width,
current_y_offset + legend_square_width)
current_x_offset += legend_label_width + (legend_square_width * 2.7)
end
index += 1
end
current_y_offset += line_height
end
end | Draws a legend with the names of the datasets matched
to the colors used to draw them. | draw_legend | ruby | topfunky/gruff | lib/gruff/base.rb | https://github.com/topfunky/gruff/blob/master/lib/gruff/base.rb | MIT |
def draw_label(x, index, gravity = Magick::NorthGravity, &block)
draw_unique_label(index) do
if x.between?(@graph_left, @graph_right)
y = @graph_bottom
x_offset, y_offset = calculate_label_offset(@marker_font, @labels[index], @label_margin, @label_rotation)
draw_label_at(1.0, 1.0, x + x_offset, y + y_offset, @labels[index], gravity: gravity, rotation: @label_rotation)
yield if block
end
end
end | Draws column labels below graph, centered over x
@rbs x: Float | Integer
@rbs index: Integer
@rbs gravity: untyped
@rbs &: () -> void | draw_label | ruby | topfunky/gruff | lib/gruff/base.rb | https://github.com/topfunky/gruff/blob/master/lib/gruff/base.rb | MIT |
def draw_label_at(width, height, x, y, text, gravity: Magick::NorthGravity, rotation: 0)
label_text = truncate_label_text(text)
text_renderer = Gruff::Renderer::Text.new(renderer, label_text, font: @marker_font, rotation: rotation)
text_renderer.add_to_render_queue(width, height, x, y, gravity)
end | @rbs width: Float | Integer
@rbs height: Float | Integer
@rbs x: Float | Integer
@rbs y: Float | Integer
@rbs text: String | _ToS
@rbs gravity: untyped
@rbs rotation: Float | Integer | draw_label_at | ruby | topfunky/gruff | lib/gruff/base.rb | https://github.com/topfunky/gruff/blob/master/lib/gruff/base.rb | MIT |
def draw_value_label(width, height, x_offset, y_offset, data_point, gravity: Magick::CenterGravity)
return if @hide_line_markers
draw_label_at(width, height, x_offset, y_offset, data_point, gravity: gravity)
end | Draws the data value over the data point in bar graphs
@rbs width: Float | Integer
@rbs height: Float | Integer
@rbs x_offset: Float | Integer
@rbs y_offset: Float | Integer
@rbs data_point: String | _ToS
@rbs gravity: untyped | draw_value_label | ruby | topfunky/gruff | lib/gruff/base.rb | https://github.com/topfunky/gruff/blob/master/lib/gruff/base.rb | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.