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 copy_file return @copy_file if defined? @copy_file @copy_file = filename + '._copy_' @copy_file.freeze end
Returns the file name to use as the temporary copy location. We are using copy-and-truncate semantics for rolling files so that the IO file descriptor remains valid during rolling.
copy_file
ruby
TwP/logging
lib/logging/appenders/rolling_file.rb
https://github.com/TwP/logging/blob/master/lib/logging/appenders/rolling_file.rb
MIT
def glob return @glob if defined? @glob m = RGXP.match @fn @glob = @fn.sub(RGXP, (m[2] ? "#{m[2]}*" : '*')) @glob.freeze end
Returns the glob pattern used to find rolled log files. We use this list for pruning older log files and doing the numbered rolling.
glob
ruby
TwP/logging
lib/logging/appenders/rolling_file.rb
https://github.com/TwP/logging/blob/master/lib/logging/appenders/rolling_file.rb
MIT
def format return @format if defined? @format m = RGXP.match @fn @format = @fn.sub(RGXP, m[1]) @format.freeze end
Returns the format String used to generate rolled file names. Depending upon the `roll_by` type (:date or :number), this String will be processed by `sprintf` or `Time#strftime`.
format
ruby
TwP/logging
lib/logging/appenders/rolling_file.rb
https://github.com/TwP/logging/blob/master/lib/logging/appenders/rolling_file.rb
MIT
def roll_files return unless roll && ::File.exist?(copy_file) files = Dir.glob(glob) files.delete copy_file self.send "roll_by_#{roll_by}", files nil ensure self.roll = false end
Roll the log files. This method will collect the list of rolled files and then pass that list to either `roll_by_number` or `roll_by_date` to perform the actual rolling. Returns nil
roll_files
ruby
TwP/logging
lib/logging/appenders/rolling_file.rb
https://github.com/TwP/logging/blob/master/lib/logging/appenders/rolling_file.rb
MIT
def roll_by_number( files ) @number_rgxp ||= Regexp.new(@fn.sub(RGXP, '\2(\d+)')) # sort the files in reverse order based on their count number files = files.sort do |a,b| a = Integer(@number_rgxp.match(a)[1]) b = Integer(@number_rgxp.match(b)[1]) b <=> a end # for each file, roll its count number one higher files.each do |fn| cnt = Integer(@number_rgxp.match(fn)[1]) if keep && cnt >= keep ::File.delete fn next end ::File.rename fn, sprintf(format, cnt+1) end # finally rename the copied log file ::File.rename(copy_file, sprintf(format, 1)) end
Roll the list of log files optionally removing older files. The "older files" are determined by extracting the number from the log file name and order by the number. files - The Array of filename Strings Returns nil
roll_by_number
ruby
TwP/logging
lib/logging/appenders/rolling_file.rb
https://github.com/TwP/logging/blob/master/lib/logging/appenders/rolling_file.rb
MIT
def roll_by_date( files ) length = files.length if keep && length >= keep files = files.sort do |a,b| a = ::File.mtime(a) b = ::File.mtime(b) b <=> a end files.last(length-keep+1).each { |fn| ::File.delete fn } end # rename the copied log file ::File.rename(copy_file, Time.now.strftime(format)) end
Roll the list of log files optionally removing older files. The "older files" are determined by the mtime of the log files. So touching log files or otherwise messing with them will screw this up. files - The Array of filename Strings Returns nil
roll_by_date
ruby
TwP/logging
lib/logging/appenders/rolling_file.rb
https://github.com/TwP/logging/blob/master/lib/logging/appenders/rolling_file.rb
MIT
def initialize( name, opts = {} ) @sio = StringIO.new @sio.extend IoToS @pos = 0 super(name, @sio, opts) end
call-seq: StringIo.new( name, opts = {} ) Creates a new StringIo appender that will append log messages to a StringIO instance.
initialize
ruby
TwP/logging
lib/logging/appenders/string_io.rb
https://github.com/TwP/logging/blob/master/lib/logging/appenders/string_io.rb
MIT
def reopen @mutex.synchronize { if defined? @io and @io flush @io.close rescue nil end @io = @sio = StringIO.new @sio.extend IoToS @pos = 0 } super self end
Reopen the underlying StringIO instance. If the instance is currently closed then it will be opened. If the instance is currently open then it will be closed and immediately opened.
reopen
ruby
TwP/logging
lib/logging/appenders/string_io.rb
https://github.com/TwP/logging/blob/master/lib/logging/appenders/string_io.rb
MIT
def clear @mutex.synchronize { @pos = 0 @sio.seek 0 @sio.truncate 0 } end
Clears the internal StringIO instance. All log messages are removed from the buffer.
clear
ruby
TwP/logging
lib/logging/appenders/string_io.rb
https://github.com/TwP/logging/blob/master/lib/logging/appenders/string_io.rb
MIT
def initialize( name, opts = {} ) @ident = opts.fetch(:ident, name) @logopt = Integer(opts.fetch(:logopt, (LOG_PID | LOG_CONS))) @facility = Integer(opts.fetch(:facility, LOG_USER)) @syslog = ::Syslog.open(@ident, @logopt, @facility) # provides a mapping from the default Logging levels # to the syslog levels @map = [LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERR, LOG_CRIT] map = opts.fetch(:map, nil) self.map = map unless map.nil? super end
call-seq: Syslog.new( name, opts = {} ) Create an appender that will log messages to the system message logger. The message is then written to the system console, log files, logged-in users, or forwarded to other machines as appropriate. The options that can be used to configure the appender are as follows: :ident => identifier string (name is used by default) :logopt => options used when opening the connection :facility => the syslog facility to use The parameter :ident is a string that will be prepended to every message. The :logopt argument is a bit field specifying logging options, which is formed by OR'ing one or more of the following values: LOG_CONS If syslog() cannot pass the message to syslogd(8) it wil attempt to write the message to the console ('/dev/console'). LOG_NDELAY Open the connection to syslogd(8) immediately. Normally the open is delayed until the first message is logged. Useful for programs that need to manage the order in which file descriptors are allocated. LOG_PERROR Write the message to standard error output as well to the system log. Not available on Solaris. LOG_PID Log the process id with each message: useful for identifying instantiations of daemons. The :facility parameter encodes a default facility to be assigned to all messages that do not have an explicit facility encoded: LOG_AUTH The authorization system: login(1), su(1), getty(8), etc. LOG_AUTHPRIV The same as LOG_AUTH, but logged to a file readable only by selected individuals. LOG_CONSOLE Messages written to /dev/console by the kernel console output driver. LOG_CRON The cron daemon: cron(8). LOG_DAEMON System daemons, such as routed(8), that are not provided for explicitly by other facilities. LOG_FTP The file transfer protocol daemons: ftpd(8), tftpd(8). LOG_KERN Messages generated by the kernel. These cannot be generated by any user processes. LOG_LPR The line printer spooling system: lpr(1), lpc(8), lpd(8), etc. LOG_MAIL The mail system. LOG_NEWS The network news system. LOG_SECURITY Security subsystems, such as ipfw(4). LOG_SYSLOG Messages generated internally by syslogd(8). LOG_USER Messages generated by random user processes. This is the default facility identifier if none is specified. LOG_UUCP The uucp system. LOG_LOCAL0 Reserved for local use. Similarly for LOG_LOCAL1 through LOG_LOCAL7.
initialize
ruby
TwP/logging
lib/logging/appenders/syslog.rb
https://github.com/TwP/logging/blob/master/lib/logging/appenders/syslog.rb
MIT
def close( footer = true ) super @syslog.close if @syslog.opened? self end
call-seq: close Closes the connection to the syslog facility.
close
ruby
TwP/logging
lib/logging/appenders/syslog.rb
https://github.com/TwP/logging/blob/master/lib/logging/appenders/syslog.rb
MIT
def reopen @mutex.synchronize { if @syslog.opened? flush @syslog.close end @syslog = ::Syslog.open(@ident, @logopt, @facility) } super self end
Reopen the connection to the underlying logging destination. If the connection is currently closed then it will be opened. If the connection is currently open then it will be closed and immediately opened.
reopen
ruby
TwP/logging
lib/logging/appenders/syslog.rb
https://github.com/TwP/logging/blob/master/lib/logging/appenders/syslog.rb
MIT
def write( event ) pri = LOG_DEBUG message = if event.instance_of?(::Logging::LogEvent) pri = @map[event.level] @layout.format(event) else event.to_s end return if message.empty? @mutex.synchronize { @syslog.log(pri, '%s', message) } self end
call-seq: write( event ) Write the given _event_ to the syslog facility. The log event will be processed through the Layout associated with this appender. The message will be logged at the level specified by the event.
write
ruby
TwP/logging
lib/logging/appenders/syslog.rb
https://github.com/TwP/logging/blob/master/lib/logging/appenders/syslog.rb
MIT
def syslog_level_num( level ) case level when Integer; level when String, Symbol level = level.to_s.upcase self.class.const_get level else raise ArgumentError, "unknown level '#{level}'" end end
call-seq: syslog_level_num( level ) => integer Takes the given _level_ as a string, symbol, or integer and returns the corresponding syslog level number.
syslog_level_num
ruby
TwP/logging
lib/logging/appenders/syslog.rb
https://github.com/TwP/logging/blob/master/lib/logging/appenders/syslog.rb
MIT
def initialize(*levels) super() levels = levels.flatten.map {|level| ::Logging::level_num(level)} @levels = Set.new(levels) end
Creates a new level filter that will only allow the given _levels_ to propagate through to the logging destination. The _levels_ should be given in symbolic form. Examples Logging::Filters::Level.new(:debug, :info)
initialize
ruby
TwP/logging
lib/logging/filters/level.rb
https://github.com/TwP/logging/blob/master/lib/logging/filters/level.rb
MIT
def allow(event) @levels.include?(event.level) ? event : nil end
Returns the event if it should be forwarded to the logging appender. Otherwise, `nil` is returned. The log event is allowed if the `event.level` matches one of the levels provided to the filter when it was constructred.
allow
ruby
TwP/logging
lib/logging/filters/level.rb
https://github.com/TwP/logging/blob/master/lib/logging/filters/level.rb
MIT
def format( event ) obj = format_obj(event.data) sprintf("%*s %s : %s\n", ::Logging::MAX_LEVEL_LENGTH, ::Logging::LNAMES[event.level], event.logger, obj) end
call-seq: format( event ) Returns a string representation of the given logging _event_. See the class documentation for details about the formatting used.
format
ruby
TwP/logging
lib/logging/layouts/basic.rb
https://github.com/TwP/logging/blob/master/lib/logging/layouts/basic.rb
MIT
def initialize( opts = {} ) super @created_at = Time.now @style = opts.fetch(:style, 'json').to_s.intern self.items = opts.fetch(:items, %w[timestamp level logger message]) end
call-seq: Parseable.new( opts ) Creates a new Parseable layout using the following options: :style => :json or :yaml :items => %w[timestamp level logger message] :utc_offset => "-06:00" or -21600 or "UTC"
initialize
ruby
TwP/logging
lib/logging/layouts/parseable.rb
https://github.com/TwP/logging/blob/master/lib/logging/layouts/parseable.rb
MIT
def format_obj( obj ) case obj when Exception hash = { :class => obj.class.name, :message => obj.message } hash[:backtrace] = obj.backtrace if backtrace? && obj.backtrace cause = format_cause(obj) hash[:cause] = cause unless cause.empty? hash when Time iso8601_format(obj) else obj end end
Public: Take a given object and convert it into a format suitable for inclusion as a log message. The conversion allows the object to be more easily expressed in YAML or JSON form. If the object is an Exception, then this method will return a Hash containing the exception class name, message, and backtrace (if any). obj - The Object to format Returns the formatted Object.
format_obj
ruby
TwP/logging
lib/logging/layouts/parseable.rb
https://github.com/TwP/logging/blob/master/lib/logging/layouts/parseable.rb
MIT
def format_cause(e) rv = curr = {} prev = nil cause_depth.times do break unless e.respond_to?(:cause) && e.cause cause = e.cause curr[:class] = cause.class.name curr[:message] = cause.message curr[:backtrace] = format_cause_backtrace(e, cause) if backtrace? && cause.backtrace prev[:cause] = curr unless prev.nil? prev, curr = curr, {} e = cause end if e.respond_to?(:cause) && e.cause prev[:cause] = {message: "Further #cause backtraces were omitted"} end rv end
Internal: Format any nested exceptions found in the given exception `e` while respecting the maximum `cause_depth`. e - Exception to format Returns the cause formatted as a Hash
format_cause
ruby
TwP/logging
lib/logging/layouts/parseable.rb
https://github.com/TwP/logging/blob/master/lib/logging/layouts/parseable.rb
MIT
def create_format_method case @style when :json; Parseable.create_json_format_method(self) when :yaml; Parseable.create_yaml_format_method(self) else raise ArgumentError, "unknown format style '#@style'" end end
Call the appropriate class level create format method based on the style of this parseable layout.
create_format_method
ruby
TwP/logging
lib/logging/layouts/parseable.rb
https://github.com/TwP/logging/blob/master/lib/logging/layouts/parseable.rb
MIT
def iso8601_format( time ) value = apply_utc_offset(time) str = value.strftime('%Y-%m-%dT%H:%M:%S') str << ('.%06d' % value.usec) offset = value.gmt_offset.abs return str << 'Z' if offset == 0 offset = sprintf('%02d:%02d', offset / 3600, offset % 3600 / 60) return str << (value.gmt_offset < 0 ? '-' : '+') << offset end
Convert the given `time` into an ISO8601 formatted time string.
iso8601_format
ruby
TwP/logging
lib/logging/layouts/parseable.rb
https://github.com/TwP/logging/blob/master/lib/logging/layouts/parseable.rb
MIT
def initialize( opts = {} ) super @created_at = Time.now.freeze @date_pattern = opts.fetch(:date_pattern, nil) @date_method = opts.fetch(:date_method, nil) @date_pattern = ISO8601 if @date_pattern.nil? && @date_method.nil? @pattern = opts.fetch(:pattern, "[%d] %-#{::Logging::MAX_LEVEL_LENGTH}l -- %c : %m\n") cs_name = opts.fetch(:color_scheme, nil) @color_scheme = case cs_name when false, nil; nil when true; ::Logging::ColorScheme[:default] else ::Logging::ColorScheme[cs_name] end self.class.create_date_format_methods(self) self.class.create_format_method(self) end
:startdoc: call-seq: Pattern.new( opts ) Creates a new Pattern layout using the following options. :pattern => "[%d] %-5l -- %c : %m\n" :date_pattern => "%Y-%m-%d %H:%M:%S" :date_method => "usec" or "to_s" :utc_offset => "-06:00" or -21600 or "UTC" :color_scheme => :default If used, :date_method will supersede :date_pattern. The :color_scheme is used to apply color formatting to the log messages. Individual tokens can be colorized witch the level token [%l] receiving distinct colors based on the level of the log event. The entire generated log message can also be colorized based on the level of the log event. See the ColorScheme documentation for more details.
initialize
ruby
TwP/logging
lib/logging/layouts/pattern.rb
https://github.com/TwP/logging/blob/master/lib/logging/layouts/pattern.rb
MIT
def _meta_eval( code, file = nil, line = nil ) meta = class << self; self end meta.class_eval code, file, line self end
:stopdoc: Evaluates the given string of `code` if the singleton class of this Pattern Layout object. Returns this Pattern Layout instance.
_meta_eval
ruby
TwP/logging
lib/logging/layouts/pattern.rb
https://github.com/TwP/logging/blob/master/lib/logging/layouts/pattern.rb
MIT
def initialize( pattern_layout ) @layout = pattern_layout @pattern = layout.pattern.dup @color_scheme = layout.color_scheme @sprintf_args = [] @format_string = '"' @name_map_count = 0 end
Creates the format method builder and initializes some variables from the given Patter layout instance. pattern_layout - The Pattern Layout instance
initialize
ruby
TwP/logging
lib/logging/layouts/pattern.rb
https://github.com/TwP/logging/blob/master/lib/logging/layouts/pattern.rb
MIT
def colorize? color_scheme && !color_scheme.lines? end
Returns `true` if the log messages should be colorized.
colorize?
ruby
TwP/logging
lib/logging/layouts/pattern.rb
https://github.com/TwP/logging/blob/master/lib/logging/layouts/pattern.rb
MIT
def colorize_lines? color_scheme && color_scheme.lines? end
Returns `true` if the log messages should be colorized by line.
colorize_lines?
ruby
TwP/logging
lib/logging/layouts/pattern.rb
https://github.com/TwP/logging/blob/master/lib/logging/layouts/pattern.rb
MIT
def colorize_levels? color_scheme && color_scheme.levels? end
Returns `true` if the log levels have special colorization defined.
colorize_levels?
ruby
TwP/logging
lib/logging/layouts/pattern.rb
https://github.com/TwP/logging/blob/master/lib/logging/layouts/pattern.rb
MIT
def build_code build_format_string sprintf = "sprintf(" sprintf << format_string sprintf << ', ' + sprintf_args.join(', ') unless sprintf_args.empty? sprintf << ")" if colorize_lines? sprintf = "color_scheme.color(#{sprintf}, ::Logging::LNAMES[event.level])" end code = "undef :format if method_defined? :format\n" code << "def format( event )\n#{sprintf}\nend\n" end
This method returns a String which can be `eval`d in the context of the Pattern layout. When it is `eval`d, a `format` method is defined in the Pattern layout. At the heart of the format method is `sprintf`. The conversion pattern specified in the Pattern layout is parsed and converted into a format string and corresponding arguments list. The format string and arguments are then processed by `sprintf` to format log events. Returns a Ruby code as a String.
build_code
ruby
TwP/logging
lib/logging/layouts/pattern.rb
https://github.com/TwP/logging/blob/master/lib/logging/layouts/pattern.rb
MIT
def build_format_string while true match = DIRECTIVE_RGXP.match(pattern) _, pre, format, directive, precision, post = *match format_string << pre unless pre.empty? case directive when '%'; format_string << '%%' when 'c'; handle_logger( format, directive, precision ) when 'l'; handle_level( format, directive, precision ) when 'X'; handle_mdc( format, directive, precision ) when 'x'; handle_ndc( format, directive, precision ) when *DIRECTIVE_TABLE.keys handle_directives(format, directive, precision) when nil; break else raise ArgumentError, "illegal format character - '#{directive}'" end break if post.empty? self.pattern = post end format_string << '"' end
This method builds the format string used by `sprintf` to format log events. The conversion pattern given by the user is iteratively parsed by a regular expression into separate format directives. Each directive builds up the format string and the corresponding arguments list that will be formatted. The actual building of the format string is handled by separate directive specific methods. Those handlers also populate the arguments list passed to `sprintf`. Returns the format String.
build_format_string
ruby
TwP/logging
lib/logging/layouts/pattern.rb
https://github.com/TwP/logging/blob/master/lib/logging/layouts/pattern.rb
MIT
def handle_logger( format, directive, slice ) fmt = format + 's' fmt = color_scheme.color(fmt, COLOR_ALIAS_TABLE[directive]) if colorize? format_string << fmt sprintf_args << DIRECTIVE_TABLE[directive].dup if slice numeric = Integer(slice) rescue nil if numeric raise ArgumentError, "logger name slice must be an integer greater than zero: #{numeric}" unless numeric > 0 sprintf_args.last << ".split(::Logging::Repository::PATH_DELIMITER)" \ ".last(#{slice}).join(::Logging::Repository::PATH_DELIMITER)" else format_string << "{#{slice}}" end end nil end
Add the logger name to the `format_string` and the `sprintf_args`. The `slice` argument is a little interesting - this is the number of logger name segments to keep. If we have a logger named "Foo::Bar::Baz" and our `slice` is 2, then "Bar::Baz" will appear in the generated log message. So the `slice` selects the last two parts of the logger name. format - format String directive - the directive character ('c') slice - the number of name segments to keep Returns nil
handle_logger
ruby
TwP/logging
lib/logging/layouts/pattern.rb
https://github.com/TwP/logging/blob/master/lib/logging/layouts/pattern.rb
MIT
def handle_level( format, directive, precision ) if colorize_levels? name_map = ::Logging::LNAMES.map { |name| color_scheme.color(("#{format}s" % name), name) } var = "@name_map_#{name_map_count}" layout.instance_variable_set(var.to_sym, name_map) self.name_map_count += 1 format_string << '%s' format_string << "{#{precision}}" if precision sprintf_args << "#{var}[event.level]" else format_string << format + 's' format_string << "{#{precision}}" if precision sprintf_args << DIRECTIVE_TABLE[directive] end nil end
Add the log event level to the `format_string` and the `sprintf_args`. The color scheme is taken into account when formatting the log event level. format - format String directive - the directive character ('l') precision - added back to the format string Returns nil
handle_level
ruby
TwP/logging
lib/logging/layouts/pattern.rb
https://github.com/TwP/logging/blob/master/lib/logging/layouts/pattern.rb
MIT
def handle_mdc( format, directive, key ) raise ArgumentError, "MDC must have a key reference" unless key fmt = format + 's' fmt = color_scheme.color(fmt, COLOR_ALIAS_TABLE[directive]) if colorize? format_string << fmt sprintf_args << "::Logging.mdc['#{key}']" nil end
Add a Mapped Diagnostic Context to the `format_string` and the `sprintf_args`. Only one MDC value is added at a time, so this directive can appear multiple times using various keys. format - format String directive - the directive character ('X') key - which MDC value to add to the log message Returns nil
handle_mdc
ruby
TwP/logging
lib/logging/layouts/pattern.rb
https://github.com/TwP/logging/blob/master/lib/logging/layouts/pattern.rb
MIT
def handle_ndc( format, directive, separator ) fmt = format + 's' fmt = color_scheme.color(fmt, COLOR_ALIAS_TABLE[directive]) if colorize? format_string << fmt separator = separator.to_s separator = ' ' if separator.empty? sprintf_args << "::Logging.ndc.context.join('#{separator}')" nil end
Add a Nested Diagnostic Context to the `format_string` and the `sprintf_args`. Since the NDC is an Array of values, the directive will appear only once in the conversion pattern. A `separator` is inserted between the values in generated log message. format - format String directive - the directive character ('x') separator - used to separate the values in the NDC array Returns nil
handle_ndc
ruby
TwP/logging
lib/logging/layouts/pattern.rb
https://github.com/TwP/logging/blob/master/lib/logging/layouts/pattern.rb
MIT
def handle_directives( format, directive, precision ) fmt = format + 's' fmt = color_scheme.color(fmt, COLOR_ALIAS_TABLE[directive]) if colorize? format_string << fmt format_string << "{#{precision}}" if precision sprintf_args << DIRECTIVE_TABLE[directive] nil end
Handles the rest of the directives; none of these need any special handling. format - format String directive - the directive character precision - added back to the format string Returns nil
handle_directives
ruby
TwP/logging
lib/logging/layouts/pattern.rb
https://github.com/TwP/logging/blob/master/lib/logging/layouts/pattern.rb
MIT
def capture_log_messages( opts = {} ) from = opts.fetch(:from, 'root') to = opts.fetch(:to, '__rspec__') exclusive = opts.fetch(:exclusive, true) appender = Logging::Appenders[to] || Logging::Appenders::StringIo.new(to) logger = Logging::Logger[from] if exclusive logger.appenders = appender else logger.add_appenders(appender) end before(:all) do @log_output = Logging::Appenders[to] end before(:each) do @log_output.reset end end
Capture log messages from the Logging framework and make them available via a @log_output instance variable. The @log_output supports a readline method to access the log messages.
capture_log_messages
ruby
TwP/logging
lib/rspec/logging_helper.rb
https://github.com/TwP/logging/blob/master/lib/rspec/logging_helper.rb
MIT
def generate_redirect_from(doc) doc.redirect_from.each do |path| page = RedirectPage.redirect_from(doc, path) doc.site.pages << page redirects[page.redirect_from] = page.redirect_to end end
For every `redirect_from` entry, generate a redirect page
generate_redirect_from
ruby
jekyll/jekyll-redirect-from
lib/jekyll-redirect-from/generator.rb
https://github.com/jekyll/jekyll-redirect-from/blob/master/lib/jekyll-redirect-from/generator.rb
MIT
def redirect_to meta_data = to_liquid["redirect_to"] meta_data.is_a?(Array) ? meta_data.compact.first : meta_data end
Returns a string representing the relative path or URL to which the document should be redirected
redirect_to
ruby
jekyll/jekyll-redirect-from
lib/jekyll-redirect-from/redirectable.rb
https://github.com/jekyll/jekyll-redirect-from/blob/master/lib/jekyll-redirect-from/redirectable.rb
MIT
def redirect_from meta_data = to_liquid["redirect_from"] meta_data.is_a?(Array) ? meta_data.compact : [meta_data].compact end
Returns an array representing the relative paths to other documents which should be redirected to this document
redirect_from
ruby
jekyll/jekyll-redirect-from
lib/jekyll-redirect-from/redirectable.rb
https://github.com/jekyll/jekyll-redirect-from/blob/master/lib/jekyll-redirect-from/redirectable.rb
MIT
def read_yaml(_base, _name, _opts = {}) self.content = self.output = "" self.data ||= DEFAULT_DATA.dup end
Overwrite the default read_yaml method since the file doesn't exist
read_yaml
ruby
jekyll/jekyll-redirect-from
lib/jekyll-redirect-from/redirect_page.rb
https://github.com/jekyll/jekyll-redirect-from/blob/master/lib/jekyll-redirect-from/redirect_page.rb
MIT
def set_paths(from, to) @context ||= context from = ensure_leading_slash(from) data.merge!( "permalink" => from, "redirect" => { "from" => from, "to" => %r!^https?://!.match?(to) ? to : absolute_url(to), } ) end
Helper function to set the appropriate path metadata from - the relative path to the redirect page to - the relative path or absolute URL to the redirect target
set_paths
ruby
jekyll/jekyll-redirect-from
lib/jekyll-redirect-from/redirect_page.rb
https://github.com/jekyll/jekyll-redirect-from/blob/master/lib/jekyll-redirect-from/redirect_page.rb
MIT
def expire_page(path) if perform_caching page_cache.expire(path) end end
Expires the page that was cached with the +path+ as a key. expire_page "/lists/show"
expire_page
ruby
rails/actionpack-page_caching
lib/action_controller/caching/pages.rb
https://github.com/rails/actionpack-page_caching/blob/master/lib/action_controller/caching/pages.rb
MIT
def cache_page(content, path, extension = nil, gzip = Zlib::BEST_COMPRESSION) if perform_caching page_cache.cache(content, path, extension, gzip) end end
Manually cache the +content+ in the key determined by +path+. cache_page "I'm the cached content", "/lists/show"
cache_page
ruby
rails/actionpack-page_caching
lib/action_controller/caching/pages.rb
https://github.com/rails/actionpack-page_caching/blob/master/lib/action_controller/caching/pages.rb
MIT
def caches_page(*actions) if perform_caching options = actions.extract_options! gzip_level = options.fetch(:gzip, page_cache_compression) gzip_level = \ case gzip_level when Symbol Zlib.const_get(gzip_level.upcase) when Integer gzip_level when false nil else Zlib::BEST_COMPRESSION end after_action({ only: actions }.merge(options)) do |c| c.cache_page(nil, nil, gzip_level) end end end
Caches the +actions+ using the page-caching approach that'll store the cache in a path within the +page_cache_directory+ that matches the triggering url. You can also pass a <tt>:gzip</tt> option to override the class configuration one. # cache the index action caches_page :index # cache the index action except for JSON requests caches_page :index, if: Proc.new { !request.format.json? } # don't gzip images caches_page :image, gzip: false
caches_page
ruby
rails/actionpack-page_caching
lib/action_controller/caching/pages.rb
https://github.com/rails/actionpack-page_caching/blob/master/lib/action_controller/caching/pages.rb
MIT
def expire_page(options = {}) if perform_caching? case options when Hash case options[:action] when Array options[:action].each { |action| expire_page(options.merge(action: action)) } else page_cache.expire(url_for(options.merge(only_path: true))) end else page_cache.expire(options) end end end
Expires the page that was cached with the +options+ as a key. expire_page controller: "lists", action: "show"
expire_page
ruby
rails/actionpack-page_caching
lib/action_controller/caching/pages.rb
https://github.com/rails/actionpack-page_caching/blob/master/lib/action_controller/caching/pages.rb
MIT
def cache_page(content = nil, options = nil, gzip = Zlib::BEST_COMPRESSION) if perform_caching? && caching_allowed? path = \ case options when Hash url_for(options.merge(only_path: true, format: params[:format])) when String options else request.path end type = if self.respond_to?(:media_type) Mime::LOOKUP[self.media_type] else Mime::LOOKUP[self.content_type] end if type && (type_symbol = type.symbol).present? extension = ".#{type_symbol}" end page_cache.cache(content || response.body, path, extension, gzip) end end
Manually cache the +content+ in the key determined by +options+. If no content is provided, the contents of response.body is used. If no options are provided, the url of the current request being handled is used. cache_page "I'm the cached content", controller: "lists", action: "show"
cache_page
ruby
rails/actionpack-page_caching
lib/action_controller/caching/pages.rb
https://github.com/rails/actionpack-page_caching/blob/master/lib/action_controller/caching/pages.rb
MIT
def swift_classes @swift_classes ||= @swift_paths .reduce([]) { |names, path| names += find(File.open(path).read) } .uniq .map {|name| SwiftClass.new(name)} end
Search all the swift paths and find things that look like classes then map those names into SwiftClasses
swift_classes
ruby
tsabend/fus
lib/fus/finder.rb
https://github.com/tsabend/fus/blob/master/lib/fus/finder.rb
MIT
def unused_classes @unused_classes ||= swift_classes.reject do |swift_class| swift_class.spec? || used_in_swift?(swift_class) || used_in_ib?(swift_class) || used_in_obj_c?(swift_class) end end
Go through the list of all Swift classes and filter out the ones that are used in Swift, IB, or Obj-C
unused_classes
ruby
tsabend/fus
lib/fus/finder.rb
https://github.com/tsabend/fus/blob/master/lib/fus/finder.rb
MIT
def find(swift_text) swift_text .scan(/(?:class|struct)\s+([a-zA-Z_]+)(?:<.+>)?\s*:?\s[a-zA-Z_<>]*\b?\s*{/) .flatten end
Given some text, identify Swift classes
find
ruby
tsabend/fus
lib/fus/finder.rb
https://github.com/tsabend/fus/blob/master/lib/fus/finder.rb
MIT
def used_in_swift?(swift_class, paths=@swift_paths) paths.any? do |path| next if swift_class.matches_classname?(path) swift_class.used_in_swift?(File.open(path).read) end end
Determines if a class is used in Swift
used_in_swift?
ruby
tsabend/fus
lib/fus/finder.rb
https://github.com/tsabend/fus/blob/master/lib/fus/finder.rb
MIT
def used_in_obj_c?(swift_class, paths=@obj_c_paths) paths.any? { |path| swift_class.used_in_obj_c?(File.open(path).read) } end
Determines if a class is used in Obj-C
used_in_obj_c?
ruby
tsabend/fus
lib/fus/finder.rb
https://github.com/tsabend/fus/blob/master/lib/fus/finder.rb
MIT
def used_in_ib?(swift_class, paths=@ib_paths) paths.any? { |path| swift_class.used_in_xml?(File.open(path).read) } end
Determines if a class is used in InterfaceBuilder
used_in_ib?
ruby
tsabend/fus
lib/fus/finder.rb
https://github.com/tsabend/fus/blob/master/lib/fus/finder.rb
MIT
def to_milliseconds(seconds) "%.3f ms" % (seconds * 1000) end
Converts seconds to milliseconds. Used to format times in the output of {MethodProfiler::Report}. @param [Float] seconds The duration to convert. @return [String] The duration in milliseconds with units displayed. Rounded to 3 decimal places.
to_milliseconds
ruby
change/method_profiler
lib/method_profiler/hirb.rb
https://github.com/change/method_profiler/blob/master/lib/method_profiler/hirb.rb
MIT
def initialize(obj) @obj = obj @data = Hash.new { |h, k| h[k] = [] } wrap_methods_with_profiling end
Initializes a new {Profiler}. Wraps all methods in the object and its singleton class with profiling code. @param [Object] obj The object to observe.
initialize
ruby
change/method_profiler
lib/method_profiler/profiler.rb
https://github.com/change/method_profiler/blob/master/lib/method_profiler/profiler.rb
MIT
def report Report.new(final_data, @obj.name) end
Generates a report object with all the data collected so far bay the profiler. This report can be displayed in various ways. See {Report}. @return [Report] A new report with all the data the profiler has collected.
report
ruby
change/method_profiler
lib/method_profiler/profiler.rb
https://github.com/change/method_profiler/blob/master/lib/method_profiler/profiler.rb
MIT
def initialize(data, name) @data = data @name = name @sort_by = :average @order = :descending end
Initializes a new {Report}. Used to sort and display data collected by a {Profiler}. @param [Array] data Data collected by a {Profiler}. @param [String] name The name of the object that was profiled.
initialize
ruby
change/method_profiler
lib/method_profiler/report.rb
https://github.com/change/method_profiler/blob/master/lib/method_profiler/report.rb
MIT
def sort_by(field) field = field.to_sym field = :average unless FIELDS.include?(field) @sort_by = field self end
Sorts the report by the given field. Defaults to `:average`. Chainable with {#order}. @param [Symbol, String] field Any field from {FIELDS} to sort by. @return [Report] The {Report} object, suitable for chaining or display.
sort_by
ruby
change/method_profiler
lib/method_profiler/report.rb
https://github.com/change/method_profiler/blob/master/lib/method_profiler/report.rb
MIT
def order(direction) direction = direction.to_sym direction = :descending unless DIRECTIONS.include?(direction) direction = :descending if direction == :desc direction = :ascending if direction == :asc @order = direction self end
Changes the direction of the sort. Defaults to `:descending`. Chainable with {#sort_by}. @param [Symbol, String] direction Any direction from {DIRECTIONS} to direct the sort. @return [Report] The {Report} object, suitable for chaining or display.
order
ruby
change/method_profiler
lib/method_profiler/report.rb
https://github.com/change/method_profiler/blob/master/lib/method_profiler/report.rb
MIT
def to_a if @order == :ascending @data.sort { |a, b| a[@sort_by] <=> b[@sort_by] } else @data.sort { |a, b| b[@sort_by] <=> a[@sort_by] } end end
Sorts the data by the currently set criteria and returns an array of profiling results. @return [Array] An array of profiling results.
to_a
ruby
change/method_profiler
lib/method_profiler/report.rb
https://github.com/change/method_profiler/blob/master/lib/method_profiler/report.rb
MIT
def to_s [ "MethodProfiler results for: #{@name}", Hirb::Helpers::Table.render( to_a, headers: HEADERS.dup, fields: FIELDS.dup, filters: { min: :to_milliseconds, max: :to_milliseconds, average: :to_milliseconds, total_time: :to_milliseconds, }, description: false ) ].join("\n") end
Sorts the data by the currently set criteria and returns a pretty printed table as a string. @return [String] A table of profiling results.
to_s
ruby
change/method_profiler
lib/method_profiler/report.rb
https://github.com/change/method_profiler/blob/master/lib/method_profiler/report.rb
MIT
def flush_asset_cache_if_necessary if settings_params.keys.include(:block_guest_comments) Asset.where(user_id: @user.id).touch_all end end
If the user changes the :block_guest_comments setting then it requires that the cache for all their tracks be invalidated
flush_asset_cache_if_necessary
ruby
sudara/alonetone
app/controllers/settings_controller.rb
https://github.com/sudara/alonetone/blob/master/app/controllers/settings_controller.rb
MIT
def find_user @user = User.find_by_login(params[:id]) not_found unless @user end
This overrides application controller's version of find_user which is too flexible, full of edge cases and deprecated.
find_user
ruby
sudara/alonetone
app/controllers/users_controller.rb
https://github.com/sudara/alonetone/blob/master/app/controllers/users_controller.rb
MIT
def find_asset @asset = Asset.with_deleted.find(params[:id]) end
find by id rather than permalink, since it's not unique include with_deleted to be able to restore
find_asset
ruby
sudara/alonetone
app/controllers/admin/assets_controller.rb
https://github.com/sudara/alonetone/blob/master/app/controllers/admin/assets_controller.rb
MIT
def respond_with_user(user) if user.valid? respond_with_valid_user(user) else render :new end end
The user argument should be a User instance that is not persisted yet. The method will save the user record, send a confirmation email, and generate a response. The user is not saved when the request or user attributes look like spam.
respond_with_user
ruby
sudara/alonetone
app/controllers/concerns/user_creation.rb
https://github.com/sudara/alonetone/blob/master/app/controllers/concerns/user_creation.rb
MIT
def awesome_truncate(text, length = 30, truncate_string = "&hellip;") return "" if text.blank? l = length - truncate_string.mb_chars.length result = text.mb_chars.length > length ? (text[/\A.{#{l}}\w*\;?/m][/.*[\w\;]/m] || '') + truncate_string : text result.html_safe end
Awesome truncate First regex truncates to the length, plus the rest of that word, if any. Second regex removes any trailing whitespace or punctuation (except ;). Unlike the regular truncate method, this avoids the problem with cutting in the middle of an entity ex.: truncate("this &amp; that",9) => "this &am..." though it will not be the exact length.
awesome_truncate
ruby
sudara/alonetone
app/helpers/application_helper.rb
https://github.com/sudara/alonetone/blob/master/app/helpers/application_helper.rb
MIT
def markdown(text) return "" unless text CommonMarker.render_doc(text, :SMART).to_html([:NOBREAKS]).html_safe end
Comments are plaintext and don't use this helper credits/profile/playlist currently are markdowned without line breaks
markdown
ruby
sudara/alonetone
app/helpers/application_helper.rb
https://github.com/sudara/alonetone/blob/master/app/helpers/application_helper.rb
MIT
def format_track_description(text) return "" unless text nofollowize(CommonMarker.render_doc(text, :SMART, [:autolink]).to_html(:HARDBREAKS)).html_safe end
full track descriptions should have hard line breaks
format_track_description
ruby
sudara/alonetone
app/helpers/application_helper.rb
https://github.com/sudara/alonetone/blob/master/app/helpers/application_helper.rb
MIT
def nofollowize(markdown) markdown.gsub('<a href', '<a rel="nofollow ugc" href') end
https://en.wikipedia.org/wiki/Nofollow#rel="ugc"
nofollowize
ruby
sudara/alonetone
app/helpers/application_helper.rb
https://github.com/sudara/alonetone/blob/master/app/helpers/application_helper.rb
MIT
def div_for(record, *args, &block) content_tag_for(:div, record, *args, &block) end
Produces a wrapper DIV element with id and class parameters that relate to the specified Active Record object. Usage example: <%= div_for(@person, class: "foo") do %> <%= @person.name %> <% end %> produces: <div id="person_123" class="person foo"> Joe Bloggs </div> You can also pass an array of Active Record objects, which will then get iterated over and yield each record as an argument for the block. For example: <%= div_for(@people, class: "foo") do |person| %> <%= person.name %> <% end %> produces: <div id="person_123" class="person foo"> Joe Bloggs </div> <div id="person_124" class="person foo"> Jane Bloggs </div>
div_for
ruby
sudara/alonetone
app/helpers/record_tag_helper.rb
https://github.com/sudara/alonetone/blob/master/app/helpers/record_tag_helper.rb
MIT
def content_tag_for(tag_name, single_or_multiple_records, prefix = nil, options = nil, &block) options, prefix = prefix, nil if prefix.is_a?(Hash) Array(single_or_multiple_records).map do |single_record| content_tag_for_single_record(tag_name, single_record, prefix, options, &block) end.join("\n").html_safe end
content_tag_for creates an HTML element with id and class parameters that relate to the specified Active Record object. For example: <%= content_tag_for(:tr, @person) do %> <td><%= @person.first_name %></td> <td><%= @person.last_name %></td> <% end %> would produce the following HTML (assuming @person is an instance of a Person object, with an id value of 123): <tr id="person_123" class="person">....</tr> If you require the HTML id attribute to have a prefix, you can specify it: <%= content_tag_for(:tr, @person, :foo) do %> ... produces: <tr id="foo_person_123" class="person">... You can also pass an array of objects which this method will loop through and yield the current object to the supplied block, reducing the need for having to iterate through the object (using <tt>each</tt>) beforehand. For example (assuming @people is an array of Person objects): <%= content_tag_for(:tr, @people) do |person| %> <td><%= person.first_name %></td> <td><%= person.last_name %></td> <% end %> produces: <tr id="person_123" class="person">...</tr> <tr id="person_124" class="person">...</tr> content_tag_for also accepts a hash of options, which will be converted to additional HTML attributes. If you specify a <tt>:class</tt> value, it will be combined with the default class name for your object. For example: <%= content_tag_for(:li, @person, class: "bar") %>... produces: <li id="person_123" class="person bar">...
content_tag_for
ruby
sudara/alonetone
app/helpers/record_tag_helper.rb
https://github.com/sudara/alonetone/blob/master/app/helpers/record_tag_helper.rb
MIT
def content_tag_for_single_record(tag_name, record, prefix, options, &block) options = options ? options.dup : {} options[:class] = [ dom_class(record, prefix), options[:class] ].compact options[:id] = dom_id(record, prefix) if block_given? content_tag(tag_name, capture(record, &block), options) else content_tag(tag_name, "", options) end end
Called by <tt>content_tag_for</tt> internally to render a content tag for each record.
content_tag_for_single_record
ruby
sudara/alonetone
app/helpers/record_tag_helper.rb
https://github.com/sudara/alonetone/blob/master/app/helpers/record_tag_helper.rb
MIT
def user_location(profile = nil) return '' unless profile locality = [profile.city.presence, profile.country.presence].compact.map(&:strip).join(', ') locality.present? ? 'from ' + locality : '' end
Returns the user's location, e.g. from Vienna, AT.
user_location
ruby
sudara/alonetone
app/helpers/users_helper.rb
https://github.com/sudara/alonetone/blob/master/app/helpers/users_helper.rb
MIT
def user_summary(user = nil) return '' unless user [ user.name, user.assets_count > 0 ? pluralize(user.assets_count, 'uploaded tracks') : nil, "Joined alonetone #{user.created_at.to_date.to_formatted_s(:long)}", user_location(user.profile).presence ].compact.join("\n") end
Returns a summary of the user's history on Alonetone.
user_summary
ruby
sudara/alonetone
app/helpers/users_helper.rb
https://github.com/sudara/alonetone/blob/master/app/helpers/users_helper.rb
MIT
def user_image_link(user = nil, variant:) white_theme_user_image_link(user, variant: variant) end
Returns an <img> element with the avatar for a user. Automatically switches to the dark theme when selected by the user.
user_image_link
ruby
sudara/alonetone
app/helpers/users_helper.rb
https://github.com/sudara/alonetone/blob/master/app/helpers/users_helper.rb
MIT
def white_theme_user_image_link(user = nil, variant:) if user link_to( user_image(user, variant: variant), user_home_path(user), title: user_summary(user) ) else user_image(user, variant: variant) end end
Returns an <a> element with the avatar for a user or an <img> element with the default avatar when the user is nil.
white_theme_user_image_link
ruby
sudara/alonetone
app/helpers/users_helper.rb
https://github.com/sudara/alonetone/blob/master/app/helpers/users_helper.rb
MIT
def user_image(user = nil, variant:) _user_image(user, url: user_avatar_url(user, variant: variant)) end
Returns an <img> tag with the avatar for the user or the default avatar when the user is nil.
user_image
ruby
sudara/alonetone
app/helpers/users_helper.rb
https://github.com/sudara/alonetone/blob/master/app/helpers/users_helper.rb
MIT
def user_avatar_url(user = nil, variant:) if user.nil? || Rails.application.show_dummy_image? UsersHelper.no_avatar_path else user.avatar_image_location(variant: variant) || UsersHelper.no_avatar_path end.to_s end
Returns a URL to the user's avatar or the default Alonetone avatar when user is nill or the user has no avatar. Always returns the default avatar when `show_dummy_image' is enabled in the config.
user_avatar_url
ruby
sudara/alonetone
app/helpers/users_helper.rb
https://github.com/sudara/alonetone/blob/master/app/helpers/users_helper.rb
MIT
def generate_asset_hash(assets) assets_array = [] assets.each do |asset| assets_array << { title: asset.title, play_link: play_link_for(asset) } if asset.title end assets_array end
I'm sure there is some fancy shmancy way to do the same thing but I can't think of it right now.
generate_asset_hash
ruby
sudara/alonetone
app/mailers/asset_notification.rb
https://github.com/sudara/alonetone/blob/master/app/mailers/asset_notification.rb
MIT
def name return title.strip if title.present? name = audio_file.attached? ? audio_file.filename.base : nil name.presence || 'untitled' end
make sure the title is there, and if not, the filename is used...
name
ruby
sudara/alonetone
app/models/asset.rb
https://github.com/sudara/alonetone/blob/master/app/models/asset.rb
MIT
def name "#{user.name}'s alonetone feature" end
The following methods help us keep dry w/ comments
name
ruby
sudara/alonetone
app/models/feature.rb
https://github.com/sudara/alonetone/blob/master/app/models/feature.rb
MIT
def cover_image_location(variant:) return unless cover_image.attached? && cover_image.persisted? Storage::Location.new( ImageVariant.variant(cover_image, variant: variant), signed: false ) end
Generates a location to playlist's cover with the requested variant. Returns nil when the playlist does not have a usable cover. As of Rails 6.0 attachables aren't persisted to storage until save https://github.com/rails/rails/pull/33303 Which means we don't want to try and display variants from unpersisted records with invalid attachments
cover_image_location
ruby
sudara/alonetone
app/models/playlist.rb
https://github.com/sudara/alonetone/blob/master/app/models/playlist.rb
MIT
def name_favorites self.title = user.name + "'s favorite tracks" if is_favorite? # move me to new tracks_controller#create self.is_mix = true if consider_a_mix? end
if this is a "favorites" playlist, give it a name/description to match
name_favorites
ruby
sudara/alonetone
app/models/playlist.rb
https://github.com/sudara/alonetone/blob/master/app/models/playlist.rb
MIT
def avatar_image_location(variant:) return unless avatar_image.attached? && avatar_image.persisted? Storage::Location.new( ImageVariant.variant(avatar_image, variant: variant), signed: false ) end
Generates a location to user's avatar with the requested variant. Returns nil when the user does not have a usable avatar. As of Rails 6.0 attachables aren't persisted to storage until save https://github.com/rails/rails/pull/33303 Which means we don't want to try and display variants from unpersisted records with invalid attachments
avatar_image_location
ruby
sudara/alonetone
app/models/user.rb
https://github.com/sudara/alonetone/blob/master/app/models/user.rb
MIT
def update_info unless controller.session[:sudo] record.last_login_at = record.current_login_at record.current_login_at = ActiveRecord.default_timezone == :utc ? Time.now.utc : Time.now record.last_login_ip = record.current_login_ip record.current_login_ip = controller.request.ip # update_info can be called before user and its associated profile is created record.profile&.update_attribute :user_agent, controller.request.user_agent end end
override authlogic's version of this to take into account @sudo
update_info
ruby
sudara/alonetone
app/models/user_session.rb
https://github.com/sudara/alonetone/blob/master/app/models/user_session.rb
MIT
def mangoz(user) ids = user&.listened_more_than?(10) && user&.listened_to_today_ids random_order.id_not_in(ids) end
random radio, without playing the same track twice in a 24 hour period
mangoz
ruby
sudara/alonetone
app/models/asset/radio.rb
https://github.com/sudara/alonetone/blob/master/app/models/asset/radio.rb
MIT
def from_favorite_artists_of(user) id_not_in(user.listened_to_today_ids) .user_id_in(user.most_listened_to_user_ids(10)) .random_order end
random radio, sourcing from the user's favorite artists
from_favorite_artists_of
ruby
sudara/alonetone
app/models/asset/radio.rb
https://github.com/sudara/alonetone/blob/master/app/models/asset/radio.rb
MIT
def guest_play_count(from = 30.days.ago) num = listens.where("listens.created_at > (?) AND listens.listener_id is null", from).count -7 + (0.19 * num.to_f) + Math.log((num.to_f + 5), 1.25) end
https://www.desmos.com/calculator/gwnliinim2 after about 20 listens, it "compresses" the value of guest listens
guest_play_count
ruby
sudara/alonetone
app/models/asset/statistics.rb
https://github.com/sudara/alonetone/blob/master/app/models/asset/statistics.rb
MIT
def make_slugs_unique slugs.each do |column, (_, scope_column)| next unless changes.key?(column.to_s) current_slug = send(column) scope_value = scope_column ? send(scope_column) : nil while self.class.slug_taken?(column, current_slug, scope_column, scope_value) current_slug = Slug.increment(current_slug) send("#{column}=", current_slug) end end end
Increments slugs when they changed and conflict with another slug.
make_slugs_unique
ruby
sudara/alonetone
app/models/concerns/slugs.rb
https://github.com/sudara/alonetone/blob/master/app/models/concerns/slugs.rb
MIT
def has_slug(column, from_attribute:, scope: nil, default: nil) slugs[column] = [from_attribute, scope] attribute(column, default: default) if default define_method("#{from_attribute}=") do |value| result = super(value) if changes.key?(from_attribute.to_s) slug = Slug.generate(result).presence || default send("#{column}=", slug) end result end end
Configures a column so its value is set based on the from_attribute. The slug value will be made unique within the defined scope. If the from_attribute does not have a value it will get the default value.
has_slug
ruby
sudara/alonetone
app/models/concerns/slugs.rb
https://github.com/sudara/alonetone/blob/master/app/models/concerns/slugs.rb
MIT
def slug_taken?(column, value, scope_column, scope_value) conditions = { column => value } conditions[scope_column] = scope_value if scope_column exists?(conditions) end
Returns true when another record with the specified column value exists in the given scope with the scope value. Author.slug_taken?(:slug, 'bob-writer', nil, nil) Book.slug_taken?(:slug, 'wonderful-life', :author_id, 54)
slug_taken?
ruby
sudara/alonetone
app/models/concerns/slugs.rb
https://github.com/sudara/alonetone/blob/master/app/models/concerns/slugs.rb
MIT
def soft_delete update_attribute(:deleted_at, Time.now) end
doesn't validate the record, calls callbacks and saves
soft_delete
ruby
sudara/alonetone
app/models/concerns/soft_deletion.rb
https://github.com/sudara/alonetone/blob/master/app/models/concerns/soft_deletion.rb
MIT
def restore update_attribute(:deleted_at, nil) end
would like to be able to skip any validation
restore
ruby
sudara/alonetone
app/models/concerns/soft_deletion.rb
https://github.com/sudara/alonetone/blob/master/app/models/concerns/soft_deletion.rb
MIT
def variant_url if Rails.application.fastly_enabled? FastlyLocation.new(attachment).url else attachment.processed.url end end
Returns a URL to either the processed image or a service URL to a service that will process the image dynamicall.
variant_url
ruby
sudara/alonetone
app/models/storage/location.rb
https://github.com/sudara/alonetone/blob/master/app/models/storage/location.rb
MIT
def original_url if Rails.application.cloudfront_enabled? CloudFrontLocation.new(attachment.key, signed: signed?).url elsif Rails.application.remote_storage? s3_url else attachment.url end end
Returns a URL to the unaltered original uploaded files.
original_url
ruby
sudara/alonetone
app/models/storage/location.rb
https://github.com/sudara/alonetone/blob/master/app/models/storage/location.rb
MIT
def with_alonetone_configuration(attributes) before = ::Rails.application.config.alonetone.dup begin ::Rails.application.config.alonetone.update(attributes) yield ensure ::Rails.application.config.alonetone = before end end
Overrides a number of configuration variables for the duration of the block.
with_alonetone_configuration
ruby
sudara/alonetone
spec/support/configuration_helpers.rb
https://github.com/sudara/alonetone/blob/master/spec/support/configuration_helpers.rb
MIT
def generate_amazon_cloud_front_private_key rsa = OpenSSL::PKey::RSA.new(2048) rsa.to_s + rsa.public_key.to_s end
Returns random RSA private and public key in PEM format as string.
generate_amazon_cloud_front_private_key
ruby
sudara/alonetone
spec/support/configuration_helpers.rb
https://github.com/sudara/alonetone/blob/master/spec/support/configuration_helpers.rb
MIT
def scrypt(input) SCrypt::Password.create( input, key_len: 32, salt_size: 8, max_mem: 1024**2, max_memfrac: 0.5, max_time: 0.2 ) end
Generate password hashes compatible with Authlogic production code.
scrypt
ruby
sudara/alonetone
spec/support/encryption_helpers.rb
https://github.com/sudara/alonetone/blob/master/spec/support/encryption_helpers.rb
MIT
def times(count) properties[:times] = count self end
Specify how many times the query should match
times
ruby
sudara/alonetone
spec/support/html_matchers.rb
https://github.com/sudara/alonetone/blob/master/spec/support/html_matchers.rb
MIT
def login(user) user = user.is_a?(User) ? user : users(user) UserSession.create!(login: user.login, password: 'test', remember_me: true) end
Creates an authenticated session for the user by changing the current test request. User passed to this method can either be a users fixture label or a User instance. Can be used in controller and view specs.
login
ruby
sudara/alonetone
spec/support/login_helpers.rb
https://github.com/sudara/alonetone/blob/master/spec/support/login_helpers.rb
MIT
def create_user_session(user) post( '/user_sessions', params: { user_session: { login: user.login, password: 'test' } } ) end
Creates an authenticated session for the user by interacting with the current integration session. Should be used in request specs.
create_user_session
ruby
sudara/alonetone
spec/support/login_helpers.rb
https://github.com/sudara/alonetone/blob/master/spec/support/login_helpers.rb
MIT