repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
contentful/contentful.rb | https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/asset.rb | lib/contentful/asset.rb | require_relative 'fields_resource'
require_relative 'file'
require_relative 'resource_references'
module Contentful
# Resource class for Asset.
# https://www.contentful.com/developers/documentation/content-delivery-api/#assets
class Asset < FieldsResource
include Contentful::ResourceReferences
# @private
def marshal_dump
super.merge(raw: raw)
end
# @private
def marshal_load(raw_object)
super(raw_object)
create_files!
define_asset_methods!
end
# @private
def known_link?(*)
false
end
# @private
def inspect
"<#{repr_name} id='#{sys[:id]}' url='#{url}'>"
end
def initialize(*)
super
create_files!
define_asset_methods!
end
# Generates a URL for the Contentful Image API
#
# @param [Hash] options
# @option options [Integer] :width
# @option options [Integer] :height
# @option options [String] :format
# @option options [String] :quality
# @option options [String] :focus
# @option options [String] :fit
# @option options [String] :fl File Layering - 'progressive'
# @option options [String] :background
# @see _ https://www.contentful.com/developers/documentation/content-delivery-api/#image-asset-resizing
#
# @return [String] Image API URL
def image_url(options = {})
query = build_query(options)
if query.empty?
file.url
else
"#{file.url}?#{URI.encode_www_form(query)}"
end
end
alias url image_url
private
def build_query(options)
{
w: options[:w] || options[:width],
h: options[:h] || options[:height],
fm: options[:fm] || options[:format],
q: options[:q] || options[:quality],
f: options[:f] || options[:focus],
bg: options[:bg] || options[:background],
r: options[:r] || options[:radius],
fit: options[:fit],
fl: options[:fl]
}.reject { |_k, v| v.nil? }
end
def create_files!
file_json = raw.fetch('fields', {}).fetch('file', nil)
return if file_json.nil?
is_localized = file_json.keys.none? { |f| %w[fileName contentType details url].include? f }
if is_localized
locales.each do |locale|
@fields[locale][:file] = ::Contentful::File.new(file_json[locale.to_s] || {}, @configuration)
end
else
@fields[internal_resource_locale][:file] = ::Contentful::File.new(file_json, @configuration)
end
end
def define_asset_methods!
define_singleton_method :title do
fields.fetch(:title, nil)
end
define_singleton_method :description do
fields.fetch(:description, nil)
end
define_singleton_method :file do |wanted_locale = nil|
fields(wanted_locale)[:file]
end
end
end
end
| ruby | MIT | 7e62f9e1accd70f9b5e01892cc42015015a92ee0 | 2026-01-04T17:44:22.911350Z | false |
contentful/contentful.rb | https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/error.rb | lib/contentful/error.rb | module Contentful
# All errors raised by the contentful gem are either instances of Contentful::Error
# or inherit from Contentful::Error
class Error < StandardError
attr_reader :response
def initialize(response)
@response = response
super best_available_message
end
# Shortcut for creating specialized error classes
# USAGE rescue Contentful::Error[404]
def self.[](error_status_code)
errors = {
400 => BadRequest,
401 => Unauthorized,
403 => AccessDenied,
404 => NotFound,
429 => RateLimitExceeded,
500 => ServerError,
502 => BadGateway,
503 => ServiceUnavailable
}
errors.key?(error_status_code) ? errors[error_status_code] : Error
end
protected
def default_error_message
"The following error was received: #{@response.raw.body}"
end
def handle_details(details)
if details.is_a?(Hash)
details.map { |k, v| "#{k.inspect}=>#{v.inspect}" }.join(', ').then { |s| "{#{s}}" }
else
details.to_s
end
end
def additional_info?
false
end
def additional_info
[]
end
def best_available_message
error_message = [
"HTTP status code: #{@response.raw.status}"
]
begin
response_json = @response.load_json
message = response_json.fetch('message', default_error_message)
details = response_json.fetch('details', nil)
request_id = response_json.fetch('requestId', nil)
error_message << "Message: #{message}"
error_message << "Details: #{handle_details(details)}" if details
error_message << "Request ID: #{request_id}" if request_id
rescue
error_message << "Message: #{default_error_message}"
end
error_message << additional_info if additional_info?
error_message.join("\n")
end
end
# 400
class BadRequest < Error
protected
def default_error_message
'The request was malformed or missing a required parameter.'
end
def handle_details(details)
return details if details.is_a?(String)
handle_detail = proc do |detail|
return detail if detail.is_a?(String)
detail.fetch('details', nil)
end
inner_details = details['errors'].map { |detail| handle_detail[detail] }.reject(&:nil?)
inner_details.join("\n\t")
end
end
# 401
class Unauthorized < Error
protected
def default_error_message
'The authorization token was invalid.'
end
end
# 403
class AccessDenied < Error
protected
def default_error_message
'The specified token does not have access to the requested resource.'
end
def handle_details(details)
"\n\tReasons:\n\t\t#{details['reasons'].join("\n\t\t")}"
end
end
# 404
class NotFound < Error
protected
def default_error_message
'The requested resource or endpoint could not be found.'
end
def handle_details(details)
return details if details.is_a?(String)
type = details['type'] || (details['sys'] || {})['type']
message = "The requested #{type} could not be found."
resource_id = details.fetch('id', nil)
message += " ID: #{resource_id}." if resource_id
message
end
end
# 429
class RateLimitExceeded < Error
# Rate Limit Reset Header Key
RATE_LIMIT_RESET_HEADER_KEY = 'x-contentful-ratelimit-reset'
def reset_time?
# rubocop:disable Style/DoubleNegation
!!reset_time
# rubocop:enable Style/DoubleNegation
end
# Time until next available request, in seconds.
def reset_time
@reset_time ||= @response.raw[RATE_LIMIT_RESET_HEADER_KEY]
end
protected
def additional_info?
reset_time?
end
def additional_info
["Time until reset (seconds): #{reset_time}"]
end
def default_error_message
'Rate limit exceeded. Too many requests.'
end
end
# 500
class ServerError < Error
protected
def default_error_message
'Internal server error.'
end
end
# 502
class BadGateway < Error
protected
def default_error_message
'The requested space is hibernated.'
end
end
# 503
class ServiceUnavailable < Error
protected
def default_error_message
'The server is currently unable to handle the request due to a temporary overloading or maintenance of the server.'
end
end
# Raised when response is no valid json
class UnparsableJson < Error
protected
def default_error_message
@response.error_message
end
end
# Raised when response is not parsable as a Contentful::Resource
class UnparsableResource < StandardError; end
# Raised when an undefined field is requested
class EmptyFieldError < StandardError
def initialize(name)
super("The field '#{name}' is empty and unavailable in the response")
end
end
end
| ruby | MIT | 7e62f9e1accd70f9b5e01892cc42015015a92ee0 | 2026-01-04T17:44:22.911350Z | false |
contentful/contentful.rb | https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/sync_page.rb | lib/contentful/sync_page.rb | require_relative 'base_resource'
require_relative 'array_like'
module Contentful
# Wrapper Class for Sync results
class SyncPage < BaseResource
include Contentful::ArrayLike
attr_reader :sync, :items, :next_sync_url, :next_page_url
def initialize(item,
configuration = {
default_locale: Contentful::Client::DEFAULT_CONFIGURATION[:default_locale]
}, *)
super(item, configuration, true)
@items = item.fetch('items', [])
@next_sync_url = item.fetch('nextSyncUrl', nil)
@next_page_url = item.fetch('nextPageUrl', nil)
end
# @private
def inspect
"<#{repr_name} next_sync_url='#{next_sync_url}' last_page=#{last_page?}>"
end
# Requests next sync page from API
#
# @return [Contentful::SyncPage, void]
def next_page
sync.get(next_page_url) if next_page?
end
# Returns wether there is a next sync page
#
# @return [Boolean]
def next_page?
# rubocop:disable Style/DoubleNegation
!!next_page_url
# rubocop:enable Style/DoubleNegation
end
# Returns wether it is the last sync page
#
# @return [Boolean]
def last_page?
!next_page_url
end
end
end
| ruby | MIT | 7e62f9e1accd70f9b5e01892cc42015015a92ee0 | 2026-01-04T17:44:22.911350Z | false |
contentful/contentful.rb | https://github.com/contentful/contentful.rb/blob/7e62f9e1accd70f9b5e01892cc42015015a92ee0/lib/contentful/support.rb | lib/contentful/support.rb | # frozen_string_literal: true
module Contentful
# Utility methods used by the contentful gem
module Support
class << self
# Transforms CamelCase into snake_case (taken from zucker)
#
# @param [String] object camelCaseName
# @param [Boolean] skip if true, skips returns original object
#
# @return [String] snake_case_name
def snakify(object, skip = false)
return object if skip
String(object)
.gsub(/::/, '/')
.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
.gsub(/([a-z\d])([A-Z])/, '\1_\2')
.tr('-', '_')
.downcase
end
def unresolvable?(value, errors)
return true if value.nil?
errors.any? { |i| i.fetch('details', {}).fetch('id', nil) == value['sys']['id'] }
end
# Checks if value is a link
#
# @param value
#
# @return [true, false]
def link?(value)
value.is_a?(::Hash) &&
value.fetch('sys', {}).fetch('type', '') == 'Link'
end
# Checks if value is an array of links
#
# @param value
#
# @return [true, false]
def link_array?(value)
return link?(value[0]) if value.is_a?(::Array) && !value.empty?
false
end
end
end
end
| ruby | MIT | 7e62f9e1accd70f9b5e01892cc42015015a92ee0 | 2026-01-04T17:44:22.911350Z | false |
codesnik/calculate-all | https://github.com/codesnik/calculate-all/blob/2e9c79c4d3f75ee6bf890697e624ca2efd0c1229/test/test_helper.rb | test/test_helper.rb | $LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)
require "logger"
require "active_record"
if ActiveSupport.respond_to?(:to_time_preserves_timezone)
ActiveSupport.to_time_preserves_timezone = :zone
end
require "calculate-all"
require "minitest/autorun"
require "minitest/reporters"
Minitest::Reporters.use! [Minitest::Reporters::SpecReporter.new(color: true)]
| ruby | MIT | 2e9c79c4d3f75ee6bf890697e624ca2efd0c1229 | 2026-01-04T17:44:30.971468Z | false |
codesnik/calculate-all | https://github.com/codesnik/calculate-all/blob/2e9c79c4d3f75ee6bf890697e624ca2efd0c1229/test/calculate_all_test.rb | test/calculate_all_test.rb | require "test_helper"
require "groupdate"
class Department < ActiveRecord::Base
has_many :orders
end
class Order < ActiveRecord::Base
belongs_to :department
end
class CalculateAllTest < Minitest::Test
def setup
@@connected ||= begin
if ENV["VERBOSE"]
ActiveRecord::Base.logger = ActiveSupport::Logger.new($stdout)
end
ActiveRecord::Migration.verbose = false
ActiveRecord::Base.establish_connection db_credentials
ActiveRecord::Migration.create_table :departments, force: true do |t|
t.string :name
end
ActiveRecord::Migration.create_table :orders, force: true do |t|
t.string :kind
t.string :currency
t.integer :department_id
t.integer :cents
t.timestamp :created_at
end
true
end
end
def teardown
Order.delete_all
Department.delete_all
end
def db_credentials
if postgresql?
{adapter: "postgresql", database: "calculate_all_test"}
elsif mysql?
{adapter: "mysql2", database: "calculate_all_test", username: "root"}
elsif sqlite?
{adapter: "sqlite3", database: ":memory:"}
else
raise "Set ENV['ADAPTER']"
end
end
def postgresql?
ENV["ADAPTER"] == "postgresql"
end
def mysql?
ENV["ADAPTER"] == "mysql"
end
def sqlite?
ENV["ADAPTER"] == "sqlite"
end
def supports_async?
Gem::Version.new(ActiveRecord.version) >= Gem::Version.new('7.1.0')
end
def create_orders
ActiveRecord::Base.transaction do
Department.create! [
{id: 1, name: "First"},
{id: 2, name: "Second"}
]
Order.create! [
{department_id: 1, kind: "card", currency: "USD", cents: 100, created_at: Time.utc(2014, 1, 3)},
{department_id: 2, kind: "card", currency: "RUB", cents: 200, created_at: Time.utc(2016, 1, 5)},
{department_id: 2, kind: "cash", currency: "USD", cents: 300, created_at: Time.utc(2014, 1, 10)},
{department_id: 1, kind: "cash", currency: "USD", cents: 400, created_at: Time.utc(2016, 5, 10)},
{department_id: 2, kind: "cash", currency: "RUB", cents: 500, created_at: Time.utc(2016, 10, 10)}
]
end
end
def test_it_has_a_version_number
refute_nil ::CalculateAll::VERSION
end
def test_no_args
assert_raises ArgumentError do
Order.all.calculate_all
end
end
def test_unknown_shortcut
assert_raises ArgumentError do
Order.all.calculate_all(:foo)
end
end
def test_model_and_no_data
assert_nil(Order.calculate_all("sum(cents)"))
end
def test_scope_and_single_expression_no_data
assert_nil(Order.all.calculate_all("sum(cents)"))
end
def test_one_group_and_no_data
assert_equal({}, Order.group(:kind).calculate_all(:cents_sum))
end
def test_many_groups_and_no_data
assert_equal({}, Order.group(:kind).group(:currency).calculate_all(:cents_sum, :count))
end
def test_one_group_one_string_expression
create_orders
expected = {
"RUB" => 700,
"USD" => 800
}
assert_equal(expected, Order.group(:currency).calculate_all("sum(cents)"))
end
def test_one_group_one_expression
create_orders
expected = {
"RUB" => {cents_sum: 700},
"USD" => {cents_sum: 800}
}
assert_equal(expected, Order.group(:currency).calculate_all(:cents_sum))
end
def test_one_group_many_expressions
create_orders
expected = {
"RUB" => {count: 2, cents_sum: 700},
"USD" => {count: 3, cents_sum: 800}
}
assert_equal(expected, Order.group(:currency).calculate_all(:count, :cents_sum))
end
def test_many_groups_many_expressions
create_orders
expected = {
["card", "USD"] => {cents_min: 100, cents_max: 100},
["cash", "USD"] => {cents_min: 300, cents_max: 400},
["card", "RUB"] => {cents_min: 200, cents_max: 200},
["cash", "RUB"] => {cents_min: 500, cents_max: 500}
}
assert_equal(expected, Order.group(:kind).group(:currency).calculate_all(:cents_min, :cents_max))
end
def test_expression_aliases
create_orders
assert_equal({foo: 2}, Order.calculate_all(foo: "count(distinct currency)"))
end
def test_returns_only_value_on_no_groups_one_string_expression
create_orders
assert_equal(400, Order.calculate_all("MAX(cents) - MIN(cents)"))
end
def test_returns_only_value_on_no_groups_and_one_expression_shortcut
create_orders
assert_equal({count_distinct_currency: 2}, Order.calculate_all(:count_distinct_currency))
end
def test_returns_grouped_values_too_when_in_list_of_expressions
create_orders
expected = {
"cash" => {kind: "cash", count: 3},
"card" => {kind: "card", count: 2}
}
assert_equal expected, Order.group(:kind).calculate_all(:kind, :count)
end
def test_returns_grouped_values_too_when_in_list_of_aliased_expressions
create_orders
expected = {
[1, "cash"] => {payment: "cash", total: 400},
[1, "card"] => {payment: "card", total: 100},
[2, "card"] => {payment: "card", total: 200},
[2, "cash"] => {payment: "cash", total: 800}
}
assert_equal expected, Order.group(:department_id, :kind).calculate_all(payment: :kind, total: :sum_cents)
end
def test_groupdate_with_simple_values
create_orders
expected = {
Date.new(2014) => 2,
Date.new(2015) => nil,
Date.new(2016) => 3
}
assert_equal expected, Order.group_by_year(:created_at).calculate_all("count(id)")
end
def test_groupdate_with_several_groups
create_orders
expected = {
["cash", Date.new(2014)] => {count: 1, sum_cents: 300},
["card", Date.new(2014)] => {count: 1, sum_cents: 100},
["cash", Date.new(2015)] => {},
["card", Date.new(2015)] => {},
["cash", Date.new(2016)] => {count: 2, sum_cents: 900},
["card", Date.new(2016)] => {count: 1, sum_cents: 200}
}
assert_equal expected, Order.group(:kind).group_by_year(:created_at).calculate_all(:count, :sum_cents)
end
def test_groupdate_with_value_wrapping
create_orders
expected = {
Date.new(2014) => "2 orders",
Date.new(2015) => "none",
Date.new(2016) => "3 orders"
}
assert_equal expected, Order.group_by_year(:created_at).calculate_all("count(*)") { |count| count ? "#{count} orders" : "none" }
end
def test_groupdate_with_several_groups_and_value_wrapping
create_orders
expected = {
["cash", Date.new(2014)] => "1 orders, 300 total",
["card", Date.new(2014)] => "1 orders, 100 total",
["cash", Date.new(2015)] => "0 orders",
["card", Date.new(2015)] => "0 orders",
["cash", Date.new(2016)] => "2 orders, 900 total",
["card", Date.new(2016)] => "1 orders, 200 total"
}
assert_equal expected, Order.group(:kind).group_by_year(:created_at).calculate_all(:count, :sum_cents) { |count: 0, sum_cents: nil|
if sum_cents
"#{count} orders, #{sum_cents} total"
else
"#{count} orders"
end
}
end
def test_value_wrapping_one_expression_and_no_groups
create_orders
assert_equal "5 orders", Order.calculate_all(:count) { |count:| "#{count} orders" }
end
def test_value_wrapping_for_one_expression
create_orders
expected = {
"RUB" => "2 orders",
"USD" => "3 orders"
}
assert_equal expected, Order.group(:currency).calculate_all(:count) { |count:|
"#{count} orders"
}
end
def test_value_wrapping_for_several_expressions
create_orders
expected = {
"RUB" => "2 orders, 350 cents average",
"USD" => "3 orders, 266 cents average"
}
assert_equal expected, Order.group(:currency).calculate_all(:count, :avg_cents) { |stats|
"#{stats[:count]} orders, #{stats[:avg_cents].to_i} cents average"
}
end
def test_value_wrapping_for_several_expressions_with_keyword_args
create_orders
expected = {
"RUB" => "2 orders, 350 cents average",
"USD" => "3 orders, 266 cents average"
}
assert_equal expected, Order.group(:currency).calculate_all(:count, :avg_cents) { |count:, avg_cents:|
"#{count} orders, #{avg_cents.to_i} cents average"
}
end
def test_value_wrapping_for_several_expressions_with_constructor
require "ostruct"
create_orders
expected = {
"RUB" => OpenStruct.new(count: 2, max_cents: 500),
"USD" => OpenStruct.new(count: 3, max_cents: 400)
}
assert_equal expected, Order.group(:currency).calculate_all(:count, :max_cents, &OpenStruct.method(:new))
end
def test_async_on_model
skip unless supports_async?
create_orders
assert_async_equal({departments: 2}, Order.async_calculate_all(departments: :count_distinct_department_id))
end
def test_async_with_groupdate_and_value_wrapping
skip unless supports_async?
create_orders
expected = {
["cash", Date.new(2014)] => "1 orders, 300 total",
["card", Date.new(2014)] => "1 orders, 100 total",
["cash", Date.new(2015)] => "0 orders",
["card", Date.new(2015)] => "0 orders",
["cash", Date.new(2016)] => "2 orders, 900 total",
["card", Date.new(2016)] => "1 orders, 200 total"
}
assert_async_equal expected,
Order.group(:kind).group_by_year(:created_at).async_calculate_all(:count, :sum_cents) { |count: 0, sum_cents: nil|
if sum_cents
"#{count} orders, #{sum_cents} total"
else
"#{count} orders"
end
}
end
def test_returns_array_on_array_aggregate
skip unless postgresql?
create_orders
expected = %W[USD RUB USD USD RUB]
assert_equal expected, Order.calculate_all("ARRAY_AGG(currency ORDER BY id)")
end
def test_returns_array_on_grouped_array_aggregate
skip unless postgresql?
create_orders
expected = {
"card" => ["USD", "RUB"],
"cash" => ["USD", "USD", "RUB"]
}
assert_equal expected, Order.group(:kind).calculate_all("ARRAY_AGG(currency ORDER BY id)")
end
def test_console
return unless ENV["CONSOLE"]
create_orders
require "irb"
IRB.start
end
private
def assert_async_equal(expected, async_result)
message = "Expected to return an ActiveRecord::Promise, got: #{async_result.inspect}"
assert_equal(true, ActiveRecord::Promise === async_result, message)
if expected.nil?
assert_nil async_result.value
else
assert_equal expected, async_result.value
end
end
end
| ruby | MIT | 2e9c79c4d3f75ee6bf890697e624ca2efd0c1229 | 2026-01-04T17:44:30.971468Z | false |
codesnik/calculate-all | https://github.com/codesnik/calculate-all/blob/2e9c79c4d3f75ee6bf890697e624ca2efd0c1229/lib/calculate-all.rb | lib/calculate-all.rb | require "active_support"
require "calculate-all/version"
module CalculateAll
# Calculates multiple aggregate values on a scope in one request, similarly to #calculate
def calculate_all(*expression_shortcuts, **named_expressions, &block)
# If only one aggregate is given as a string or Arel.sql without explicit naming,
# return row(s) directly without wrapping in Hash
if expression_shortcuts.size == 1 && expression_shortcuts.first.is_a?(String) &&
named_expressions.size == 0
return_plain_values = true
end
named_expressions = expression_shortcuts.index_by(&:itself).merge(named_expressions)
named_expressions.transform_values! do |shortcut|
Helpers.decode_expression_shortcut(shortcut, group_values)
end
raise ArgumentError, "provide at least one expression to calculate" if named_expressions.empty?
# Some older active_record versions do not allow for repeating expressions in pluck list,
# and named expressions could contain group values.
columns = (group_values + named_expressions.values).uniq
value_mapping = named_expressions.transform_values { |column| columns.index(column) }
columns.map! { |column| column.is_a?(String) ? Arel.sql(column) : column }
pluck(*columns).then do |rows|
results = rows.to_h do |row|
# If pluck called with a single argument
# it will return an array of scalars instead of array of arrays
row = [row] if columns.size == 1
key = if group_values.size == 0
:ALL
elsif group_values.size == 1
# If only one group is provided, the resulting key is just a scalar value
row.first
else
# if multiple groups, the key will be an array.
row.first(group_values.size)
end
value = value_mapping.transform_values { |index| row[index] }
value = value.values.last if return_plain_values
[key, value]
end
# Additional groupdate magic of filling empty periods with defaults
if defined?(Groupdate.process_result)
# Since that hash is the same instance for every backfilled row, at least
# freeze it to prevent surprise modifications across multiple rows in the calling code.
default_value = return_plain_values ? nil : {}.freeze
results = Groupdate.process_result(self, results, default_value: default_value)
end
if block
results.transform_values! do |value|
return_plain_values ? block.call(value) : block.call(**value)
end
end
# Return unwrapped hash directly for scope without any .group()
if group_values.empty?
results[:ALL]
else
results
end
end
end
if Gem::Version.new(ActiveRecord.version) >= Gem::Version.new('7.1.0')
def async_calculate_all(*expression_shortcuts, **named_expressions, &block)
async.calculate_all(*expression_shortcuts, **named_expressions, &block)
end
end
# module just to not pollute namespace
module Helpers
module_function
# Convert shortcuts like :count_distinct_id to SQL aggregate functions like 'COUNT(DISTINCT ID)'
# If shortcut is actually one of the grouping expressions, just return it as-is.
def decode_expression_shortcut(shortcut, group_values = [])
case shortcut
when String
shortcut
when *group_values
shortcut
when :count
"COUNT(*)"
when /^(\w+)_distinct_count$/, /^count_distinct_(\w+)$/
"COUNT(DISTINCT #{$1})"
when /^(\w+)_(count|sum|max|min|avg)$/
"#{$2.upcase}(#{$1})"
when /^(count|sum|max|min|avg)_(\w+)$/
"#{$1.upcase}(#{$2})"
when /^(\w+)_average$/, /^average_(\w+)$/
"AVG(#{$1})"
when /^(\w+)_maximum$/, /^maximum_(\w+)$/
"MAX(#{$1})"
when /^(\w+)_minimum$/, /^minimum_(\w+)$/
"MIN(#{$1})"
else
raise ArgumentError, "Can't recognize expression shortcut #{shortcut}"
end
end
end
module Querying
# see CalculateAll#calculate_all
def calculate_all(*expression_shortcuts, **named_expressions, &block)
all.calculate_all(*expression_shortcuts, **named_expressions, &block)
end
if Gem::Version.new(ActiveRecord.version) >= Gem::Version.new('7.1.0')
# see CalculateAll#async_calculate_all
def async_calculate_all(*expression_shortcuts, **named_expressions, &block)
all.async_calculate_all(*expression_shortcuts, **named_expressions, &block)
end
end
end
end
ActiveSupport.on_load(:active_record) do
# Make the calculate_all method available for all ActiveRecord::Relations instances
ActiveRecord::Relation.include CalculateAll
# Make the calculate_all method available for all ActiveRecord::Base classes
# You can for example call Orders.calculate_all(:count, :sum_cents)
ActiveRecord::Base.extend CalculateAll::Querying
end
| ruby | MIT | 2e9c79c4d3f75ee6bf890697e624ca2efd0c1229 | 2026-01-04T17:44:30.971468Z | false |
codesnik/calculate-all | https://github.com/codesnik/calculate-all/blob/2e9c79c4d3f75ee6bf890697e624ca2efd0c1229/lib/calculate-all/version.rb | lib/calculate-all/version.rb | module CalculateAll
VERSION = "0.4.0"
end
| ruby | MIT | 2e9c79c4d3f75ee6bf890697e624ca2efd0c1229 | 2026-01-04T17:44:30.971468Z | false |
sinisterchipmunk/rspec-prof | https://github.com/sinisterchipmunk/rspec-prof/blob/9e01c8f00753047cf9ba28c7d1332549bfbb7469/features/support/reset_env.rb | features/support/reset_env.rb | After do
ENV.delete 'RSPEC_PROFILE'
end
| ruby | MIT | 9e01c8f00753047cf9ba28c7d1332549bfbb7469 | 2026-01-04T17:44:31.182003Z | false |
sinisterchipmunk/rspec-prof | https://github.com/sinisterchipmunk/rspec-prof/blob/9e01c8f00753047cf9ba28c7d1332549bfbb7469/features/support/env.rb | features/support/env.rb | require 'aruba/cucumber'
Before do
@aruba_timeout_seconds = 60
end
| ruby | MIT | 9e01c8f00753047cf9ba28c7d1332549bfbb7469 | 2026-01-04T17:44:31.182003Z | false |
sinisterchipmunk/rspec-prof | https://github.com/sinisterchipmunk/rspec-prof/blob/9e01c8f00753047cf9ba28c7d1332549bfbb7469/features/support/spec_helper.rb | features/support/spec_helper.rb | Before do |scenario|
step 'a file named "spec/spec_helper.rb" with:', <<-end_file
require 'simplecov'
require 'coveralls'
SimpleCov.start do
root "#{File.expand_path('../..', File.dirname(__FILE__))}"
coverage_dir 'coverage'
SimpleCov.command_name #{scenario.name.inspect}
filters.clear
add_filter { |f| !f.filename['rspec-prof'] }
end
require 'rspec-prof'
end_file
end
| ruby | MIT | 9e01c8f00753047cf9ba28c7d1332549bfbb7469 | 2026-01-04T17:44:31.182003Z | false |
sinisterchipmunk/rspec-prof | https://github.com/sinisterchipmunk/rspec-prof/blob/9e01c8f00753047cf9ba28c7d1332549bfbb7469/features/step_definitions/environment_variable_steps.rb | features/step_definitions/environment_variable_steps.rb | Given(/^the environment variable "(.*?)" is set to "(.*?)"$/) do |arg1, arg2|
ENV[arg1] = arg2
end
| ruby | MIT | 9e01c8f00753047cf9ba28c7d1332549bfbb7469 | 2026-01-04T17:44:31.182003Z | false |
sinisterchipmunk/rspec-prof | https://github.com/sinisterchipmunk/rspec-prof/blob/9e01c8f00753047cf9ba28c7d1332549bfbb7469/features/step_definitions/pass_fail_steps.rb | features/step_definitions/pass_fail_steps.rb | Then(/^it should (pass|fail)$/) do |pass_fail|
step "it should #{pass_fail} with:", ""
end
| ruby | MIT | 9e01c8f00753047cf9ba28c7d1332549bfbb7469 | 2026-01-04T17:44:31.182003Z | false |
sinisterchipmunk/rspec-prof | https://github.com/sinisterchipmunk/rspec-prof/blob/9e01c8f00753047cf9ba28c7d1332549bfbb7469/lib/rspec-prof.rb | lib/rspec-prof.rb | require 'fileutils'
require 'ruby-prof'
require 'rspec/core'
require 'rspec-prof/filename_helpers'
class RSpecProf
extend FilenameHelpers
@printer_class = RubyProf::GraphHtmlPrinter
class << self
attr_accessor :printer_class
def profile filename
profiler = new.start
yield
ensure
profiler.save_to filename
end
end
def start
return if @profiling
@profiling = true
RubyProf.start
self
end
def stop
return unless @profiling
@profiling = false
@result = RubyProf.stop
end
def profiling?
@profiling
end
def result
@result
end
def save_to filename
stop
FileUtils.mkdir_p File.dirname(filename)
File.open(filename, "w") do |f|
printer = RSpecProf.printer_class.new(result)
printer.print(f, :min_percent => 1)
end
end
end
RSpec.configure do |config|
profiler = nil
config.before(:suite) do
unless ['all', 'each', ''].include?(ENV['RSPEC_PROFILE'].to_s)
raise "ENV['RSPEC_PROFILE'] should be blank, 'all' or 'each', but was '#{ENV['RSPEC_PROFILE']}'"
end
if ENV['RSPEC_PROFILE'] == 'all'
profiler = RSpecProf.new.start
end
end
config.after(:suite) do
if ENV['RSPEC_PROFILE'] == 'all'
profiler.save_to "#{RSpecProf.output_dir}/all.#{RSpecProf.file_extension}"
end
end
config.around(:each) do |example|
if ENV['RSPEC_PROFILE'] == 'each'
RSpecProf.profile(RSpecProf.filename_for(example)) { example.call }
else
example.call
end
end
end
| ruby | MIT | 9e01c8f00753047cf9ba28c7d1332549bfbb7469 | 2026-01-04T17:44:31.182003Z | false |
sinisterchipmunk/rspec-prof | https://github.com/sinisterchipmunk/rspec-prof/blob/9e01c8f00753047cf9ba28c7d1332549bfbb7469/lib/rspec-prof/filename_helpers.rb | lib/rspec-prof/filename_helpers.rb | class RSpecProf
module FilenameHelpers
@output_dir = "profiles"
@file_extension = "html"
class << self
attr_accessor :output_dir
attr_accessor :file_extension
end
def output_dir
RSpecProf::FilenameHelpers.output_dir
end
def file_extension
RSpecProf::FilenameHelpers.file_extension
end
def path_for metadata
if metadata[:parent_example_group]
File.join(path_for(metadata[:parent_example_group]), metadata[:description])
else
metadata[:description]
end
end
def filename_for example
path = path_for(example.metadata[:example_group])
line_number = example.metadata[:line_number].to_s
description = example.metadata[:description]
File.join(
output_dir,
path,
description
).gsub(/\s+/, '-') + ":" + line_number + ".#{file_extension}"
end
end
end
| ruby | MIT | 9e01c8f00753047cf9ba28c7d1332549bfbb7469 | 2026-01-04T17:44:31.182003Z | false |
sous-chefs/users | https://github.com/sous-chefs/users/blob/d62a03c765febf45464763207965ab7d6ac523ba/metadata.rb | metadata.rb | name 'users'
maintainer 'Sous Chefs'
maintainer_email 'help@sous-chefs.org'
license 'Apache-2.0'
description 'Creates users from a databag search'
version '8.1.24'
source_url 'https://github.com/sous-chefs/users'
issues_url 'https://github.com/sous-chefs/users/issues'
chef_version '>= 15.3'
supports 'aix'
supports 'amazon'
supports 'centos'
supports 'debian'
supports 'fedora'
supports 'freebsd'
supports 'mac_os_x'
supports 'opensuse'
supports 'opensuseleap'
supports 'oracle'
supports 'redhat'
supports 'scientific'
supports 'suse'
supports 'ubuntu'
supports 'zlinux'
# supports 'windows'
| ruby | Apache-2.0 | d62a03c765febf45464763207965ab7d6ac523ba | 2026-01-04T17:44:31.220288Z | false |
sous-chefs/users | https://github.com/sous-chefs/users/blob/d62a03c765febf45464763207965ab7d6ac523ba/test/integration/default/default_spec.rb | test/integration/default/default_spec.rb | os_family = os.family
# Test if the groups exist
describe group('testgroup') do
it { should exist }
its('gid') { should eq 3000 }
end
describe group('nfsgroup') do
it { should exist }
its('gid') { should eq 4000 }
end
describe group('emptygroup') do
it { should exist }
its('gid') { should eq 5000 }
if os_family == 'darwin'
its('members') { should eq [] }
else
its('members') { should eq '' }
end
end
describe group('explicituser') do
it { should exist }
end
# Test users from attributes
describe user('usertoremove') do
it { should_not exist }
end
describe user('user_with_dev_null_home') do
it { should exist }
its('uid') { should eq 5000 } unless os_family == 'darwin'
its('gid') { should eq 4000 } unless os_family == 'darwin'
case os_family
when 'suse'
its('groups') { should eq %w( nfsgroup ) }
when 'darwin'
its('groups') { should include 'nfsgroup' }
else
its('groups') { should eq %w( nfsgroup ) }
end
its('shell') { should eq '/bin/bash' }
end
describe user('user_with_nfs_home_first') do
it { should exist }
case os_family
when 'suse'
its('groups') { should eq %w( users nfsgroup ) }
when 'darwin'
its('groups') { should include 'nfsgroup' }
else
its('groups') { should eq %w( user_with_nfs_home_first nfsgroup ) }
end
its('shell') { should eq '/bin/sh' }
end
describe directory('/home/user_with_nfs_home_first') do
it { should exist }
its('owner') { should cmp 'user_with_nfs_home_first' }
case os_family
when 'suse'
its('group') { should cmp 'users' }
else
its('group') { should cmp 'user_with_nfs_home_first' }
end
end unless os_family == 'darwin'
describe directory('/home/user_with_nfs_home_second') do
it { should exist }
its('owner') { should cmp 'user_with_nfs_home_second' }
case os_family
when 'suse'
its('group') { should cmp 'users' }
else
its('group') { should cmp 'user_with_nfs_home_second' }
end
end unless os_family == 'darwin'
describe directory('/home/user_with_local_home') do
it { should exist }
its('owner') { should cmp 'user_with_local_home' }
case os_family
when 'suse'
its('group') { should cmp 'users' }
else
its('group') { should cmp 'user_with_local_home' }
end
end unless os_family == 'darwin'
describe directory('/home/user_with_username_instead_of_id') do
it { should exist }
its('owner') { should cmp 'user_with_username_instead_of_id' }
case os_family
when 'suse'
its('group') { should cmp 'users' }
else
its('group') { should cmp 'user_with_username_instead_of_id' }
end
end unless os_family == 'darwin'
describe file('/home/user_with_nfs_home_first/.ssh/id_ed25519.pub') do
its('content') { should include('ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIC6aZDF+x28xIlZSgyfyh3IAkencLp1VCU7JXBhJcXNy cheftestuser@laptop') }
end unless os_family == 'darwin' # InSpec runs as non-root and can't see these files
describe user('user_with_nfs_home_second') do
it { should exist }
case os_family
when 'suse'
its('groups') { should eq %w( users nfsgroup ) }
when 'darwin'
its('groups') { should include 'nfsgroup' }
else
its('groups') { should eq %w( user_with_nfs_home_second nfsgroup ) }
end
its('shell') { should eq '/bin/sh' }
end
describe file('/home/user_with_nfs_home_second/.ssh/id_ecdsa') do
it { should exist }
its('content') { should include("-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNlY2RzYS\n1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQQns8Ec3poQBm6r7zv/UZojvXjrUZVB\n59R4LzOBw8cS/2xSQrVH8qm2X8kB1y6nuyydK0bbQF1pnES1P+uvG6e9AAAAsD2Nf449jX\n+OAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBCezwRzemhAGbqvv\nO/9RmiO9eOtRlUHn1HgvM4HDxxL/bFJCtUfyqbZfyQHXLqe7LJ0rRttAXWmcRLU/668bp7\n0AAAAgJp/B6o2OADM0+NlkgH1dFcOLK64jhr3ScbWK4iyRdOcAAAAVZm11bGxlckBzYnBs\ndGMxbWxsdmRsAQID\n-----END OPENSSH PRIVATE KEY-----\n") }
its('owner') { should eq 'user_with_nfs_home_second' }
case os_family
when 'suse'
its('group') { should eq 'users' }
else
its('group') { should eq 'user_with_nfs_home_second' }
end
end unless os_family == 'darwin' # InSpec runs as non-root and can't see these files
describe file('/home/user_with_nfs_home_second/.ssh/id_ecdsa.pub') do
it { should exist }
its('content') { should include('ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBCezwRzemhAGbqvvO/9RmiO9eOtRlUHn1HgvM4HDxxL/bFJCtUfyqbZfyQHXLqe7LJ0rRttAXWmcRLU/668bp70=') }
its('owner') { should eq 'user_with_nfs_home_second' }
case os_family
when 'suse'
its('group') { should eq 'users' }
else
its('group') { should eq 'user_with_nfs_home_second' }
end
end unless os_family == 'darwin' # InSpec runs as non-root and can't see these files
describe user('user_with_local_home') do
it { should exist }
case os_family
when 'suse'
its('groups') { should eq %w( users nfsgroup ) }
when 'darwin'
its('groups') { should include 'nfsgroup' }
else
its('groups') { should eq %w( user_with_local_home nfsgroup ) }
end
its('shell') { should eq '/bin/sh' }
end
describe user('explicituser') do
it { should exist }
case os_family
when 'darwin'
%w(staff explicituser).each do |g|
its('groups') { should include g }
end
when 'suse'
its('groups') { should eq %w( users explicituser ) }
else
its('groups') { should eq %w( explicituser ) }
end
end
describe directory('/home/user_with_local_home') do
it { should exist }
its('owner') { should eq 'user_with_local_home' }
case os_family
when 'suse'
its('group') { should eq 'users' }
else
its('group') { should eq 'user_with_local_home' }
end
end unless os_family == 'darwin' # InSpec runs as non-root and can't see these files
describe file('/home/user_with_local_home/.ssh/id_rsa') do
it { should exist }
its('content') { should include("-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\nQyNTUxOQAAACAummQxfsdvMSJWUoMn8odyAJHp3C6dVQlOyVwYSXFzcgAAAJjzcJxA83Cc\nQAAAAAtzc2gtZWQyNTUxOQAAACAummQxfsdvMSJWUoMn8odyAJHp3C6dVQlOyVwYSXFzcg\nAAAEC7TGfA0MU0mh0V39qw5RSThUo0idTtU2vCe9bJrHmyFS6aZDF+x28xIlZSgyfyh3IA\nkencLp1VCU7JXBhJcXNyAAAAFWZtdWxsZXJAc2JwbHRjMW1sbHZkbA==\n-----END OPENSSH PRIVATE KEY-----\n") }
end unless os_family == 'darwin' # InSpec runs as non-root and can't see these files
describe user('user_with_username_instead_of_id') do
it { should exist }
case os_family
when 'suse'
its('groups') { should eq %w( users nfsgroup ) }
when 'darwin'
its('groups') { should include 'nfsgroup' }
else
its('groups') { should eq %w( user_with_username_instead_of_id nfsgroup ) }
end
its('shell') { should eq '/bin/bash' }
end
describe directory('/home/user_with_username_instead_of_id') do
it { should exist }
its('owner') { should eq 'user_with_username_instead_of_id' }
case os_family
when 'suse'
its('group') { should eq 'users' }
else
its('group') { should eq 'user_with_username_instead_of_id' }
end
end unless os_family == 'darwin'
describe directory('/home/user_with_username_instead_of_id/.ssh') do
it { should exist }
its('owner') { should eq 'user_with_username_instead_of_id' }
case os_family
when 'suse'
its('group') { should eq 'users' }
else
its('group') { should eq 'user_with_username_instead_of_id' }
end
end unless os_family == 'darwin'
describe file('/home/user_with_username_instead_of_id/.ssh/authorized_keys') do
it { should exist }
its('owner') { should eq 'user_with_username_instead_of_id' }
case os_family
when 'suse'
its('group') { should eq 'users' }
else
its('group') { should eq 'user_with_username_instead_of_id' }
end
its('content') { should include('ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIC6aZDF+x28xIlZSgyfyh3IAkencLp1VCU7JXBhJcXNy cheftestuser@laptop') }
end unless os_family == 'darwin'
describe file('/home/user_with_username_instead_of_id/.ssh/id_ecdsa') do
it { should exist }
its('owner') { should eq 'user_with_username_instead_of_id' }
case os_family
when 'suse'
its('group') { should eq 'users' }
when 'darwin'
its('group') { should eq 'staff' }
else
its('group') { should eq 'user_with_username_instead_of_id' }
end
its('content') { should include("-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\nQyNTUxOQAAACAummQxfsdvMSJWUoMn8odyAJHp3C6dVQlOyVwYSXFzcgAAAJjzcJxA83Cc\nQAAAAAtzc2gtZWQyNTUxOQAAACAummQxfsdvMSJWUoMn8odyAJHp3C6dVQlOyVwYSXFzcg\nAAAEC7TGfA0MU0mh0V39qw5RSThUo0idTtU2vCe9bJrHmyFS6aZDF+x28xIlZSgyfyh3IA\nkencLp1VCU7JXBhJcXNyAAAAFWZtdWxsZXJAc2JwbHRjMW1sbHZkbA==\n-----END OPENSSH PRIVATE KEY-----\n") }
end unless os_family == 'darwin'
describe file('/home/user_with_username_instead_of_id/.ssh/id_ecdsa.pub') do
it { should exist }
its('owner') { should eq 'user_with_username_instead_of_id' }
case os_family
when 'suse'
its('group') { should eq 'users' }
when 'darwin'
its('group') { should eq 'staff' }
else
its('group') { should eq 'user_with_username_instead_of_id' }
end
its('content') { should include('ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBCezwRzemhAGbqvvO/9RmiO9eOtRlUHn1HgvM4HDxxL/bFJCtUfyqbZfyQHXLqe7LJ0rRttAXWmcRLU/668bp70=') }
end unless os_family == 'darwin'
# Test users from databags
describe user('databag_mwaddams') do
it { should_not exist }
end
describe directory('/home/databag_mwaddams') do
it { should_not exist }
end
describe group('databag_mwaddams') do
it { should_not exist }
end
describe user('databag_test_user') do
it { should exist }
its('uid') { should eq 9001 } unless os_family == 'darwin'
case os_family
when 'suse'
its('groups') { should eq %w( users testgroup ) }
when 'darwin'
its('groups') { should include 'testgroup' }
else
its('groups') { should eq %w( databag_test_user testgroup ) }
end
its('shell') { should eq '/bin/bash' }
end
describe user('databag_test_user_keys_from_url') do
it { should exist }
its('uid') { should eq 9002 } unless os_family == 'darwin'
case os_family
when 'suse'
its('groups') { should eq %w( users testgroup ) }
when 'darwin'
its('groups') { should include 'testgroup' }
else
its('groups') { should eq %w( databag_test_user_keys_from_url testgroup ) }
end
its('shell') { should eq '/bin/bash' }
end
# NOTE: this test is super brittle and should probably create a specific github
# user or mock an HTTP server with the keys
ssh_keys = [
'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCy3cbPekJYHAIa8J1fOr2iIqpx/7pl4giJYAG7HCfsunRRUq3dY1KhVw1BlmMGIDzNwcuNVIfBS5HS/wREqbHMXxbwAjWrMwUofWd09CTuKJZiyTLUC5pSQWKDXZrefH/Fwd7s+YKk1s78b49zkyDcHSnKxjN+5veinzeU+vaUF9duFAJ9OsL7kTDEzOUU0zJdSdUV0hH1lnljnvk8kXHLFl9sKS3iM2LRqW4B6wOc2RbXUnx+jwNaBsq1zd73F2q3Ta7GXdtW/q4oDYl3s72oW4ySL6TZfpLCiv/7txHicZiY1eqc591CON0k/Rh7eR7XsphwkUstoUPQcBuLqQPA529zBigD7A8PBmeHISxL2qirWjR2+PrEGn1b0yu8IHHz9ZgliX83Q4WpjXvJ3REj2jfM8hiFRV3lA/ovjQrmLLV8WUAZ8updcLE5mbhZzIsC4U/HKIJS02zoggHGHZauClwwcdBtIJnJqtP803yKNPO2sDudTpvEi8GZ8n6jSXo/N8nBVId2LZa5YY/g/v5kH0akn+/E3jXhw4CICNW8yICpeJO8dGYMOp3Bs9/cRK8QYomXqgpoFlvkgzT2h4Ie6lyRgNv5QnUyAnW43O5FdBnPk/XZ3LA462VU3uOfr0AQtEJzPccpFC6OCFYWdGwZQA/r1EZQES0yRfJLpx+uZQ==',
'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCy3cbPekJYHAIa8J1fOr2iIqpx/7pl4giJYAG7HCfsunRRUq3dY1KhVw1BlmMGIDzNwcuNVIfBS5HS/wREqbHMXxbwAjWrMwUofWd09CTuKJZiyTLUC5pSQWKDXZrefH/Fwd7s+YKk1s78b49zkyDcHSnKxjN+5veinzeU+vaUF9duFAJ9OsL7kTDEzOUU0zJdSdUV0hH1lnljnvk8kXHLFl9sKS3iM2LRqW4B6wOc2RbXUnx+jwNaBsq1zd73F2q3Ta7GXdtW/q4oDYl3s72oW4ySL6TZfpLCiv/7txHicZiY1eqc591CON0k/Rh7eR7XsphwkUstoUPQcBuLqQPA529zBigD7A8PBmeHISxL2qirWjR2+PrEGn1b0yu8IHHz9ZgliX83Q4WpjXvJ3REj2jfM8hiFRV3lA/ovjQrmLLV8WUAZ8updcLE5mbhZzIsC4U/HKIJS02zoggHGHZauClwwcdBtIJnJqtP803yKNPO2sDudTpvEi8GZ8n6jSXo/N8nBVId2LZa5YY/g/v5kH0akn+/E3jXhw4CICNW8yICpeJO8dGYMOp3Bs9/cRK8QYomXqgpoFlvkgzT2h4Ie6lyRgNv5QnUyAnW43O5FdBnPk/XZ3LA462VU3uOfr0AQtEJzPccpFC6OCFYWdGwZQA/r1EZQES0yRfJLpx+uZQ==',
]
describe file('/home/databag_test_user_keys_from_url/.ssh/authorized_keys') do
ssh_keys.each do |key|
its('content') { should include(key) }
its('owner') { should eq 'databag_test_user_keys_from_url' }
case os_family
when 'suse'
its('group') { should eq 'users' }
else
its('group') { should eq 'databag_test_user_keys_from_url' }
end
end
end unless os_family == 'darwin' # InSpec runs as non-root and can't see these files
describe user('joins_spawned_group') do
it { should exist }
case os_family
when 'darwin'
%w(string_gid user_before_group).each do |g|
its('groups') { should include g }
end
else
its('groups') { should eq %w(string_gid user_before_group) }
end
end
describe user('primary_integer_gid') do
it { should exist }
case os_family
when 'darwin'
%w(user_before_group spawns_next_group).each do |g|
its('groups') { should include g }
end
when 'suse'
its('groups') { should eq %w(user_before_group spawns_next_group) }
else
its('groups') { should eq %w(user_before_group spawns_next_group primary_integer_gid) }
end
end
describe directory('/home/joins_spawned_group') do
it { should exist }
its('owner') { should eq 'joins_spawned_group' }
its('group') { should eq 'string_gid' }
end unless os_family == 'darwin'
describe directory('/home/primary_integer_gid') do
it { should exist }
its('owner') { should eq 'primary_integer_gid' }
its('group') { should eq 'user_before_group' }
end unless os_family == 'darwin'
describe directory('/home/nonstandard_homedir_perms') do
it { should exist }
its('owner') { should eq 'nonstandard_homedir_perms' }
case os_family
when 'suse'
its('group') { should eq 'users' }
when 'darwin'
its('group') { should eq nil }
else
its('group') { should eq 'nonstandard_homedir_perms' }
end
its('mode') { should cmp '02755' }
end unless os_family == 'darwin'
describe directory('/home/nonstandard_homedir_perms/.ssh') do
it { should exist }
its('owner') { should eq 'nonstandard_homedir_perms' }
case os_family
when 'suse'
its('group') { should eq 'users' }
else
its('group') { should eq 'nonstandard_homedir_perms' }
end
its('mode') { should cmp '0700' }
end unless os_family == 'darwin'
describe user('username_gid') do
it { should exist }
case os_family
when 'suse'
its('groups') { should cmp %w(users testgroup) }
when 'darwin'
%w(staff testgroup).each do |g|
its('groups') { should include g }
end
else
its('groups') { should cmp %w(username_gid testgroup) }
its('gid') { should eq 7000 }
end
end
describe user('system_user') do
it { should exist }
its('uid') { should be < 1000 } unless os_family == 'darwin'
end
describe group('system_group') do
it { should exist }
its('gid') { should be < 1000 } unless os_family == 'darwin'
end
| ruby | Apache-2.0 | d62a03c765febf45464763207965ab7d6ac523ba | 2026-01-04T17:44:31.220288Z | false |
sous-chefs/users | https://github.com/sous-chefs/users/blob/d62a03c765febf45464763207965ab7d6ac523ba/test/fixtures/cookbooks/users_test/metadata.rb | test/fixtures/cookbooks/users_test/metadata.rb | name 'users_test'
maintainer 'Chef Software, Inc.'
maintainer_email 'cookbooks@chef.io'
license 'Apache-2.0'
description 'Tests the users cookbook'
version '1.7.1'
depends 'users'
| ruby | Apache-2.0 | d62a03c765febf45464763207965ab7d6ac523ba | 2026-01-04T17:44:31.220288Z | false |
sous-chefs/users | https://github.com/sous-chefs/users/blob/d62a03c765febf45464763207965ab7d6ac523ba/test/fixtures/cookbooks/users_test/recipes/default.rb | test/fixtures/cookbooks/users_test/recipes/default.rb | user 'databag_mwaddams' do
manage_home true
action :nothing
end
# Get the users from the data bag
users = search('test_home_dir', '*:*')
# Create the users from the data bag.
users_manage 'testgroup' do
users users
group_id 3000
action [:remove, :create]
notifies :create, 'user[databag_mwaddams]', :before
end
# Create the users from an attribute
users_manage 'nfsgroup' do
users node['users_test']['users']
group_id 4000
action [:remove, :create]
manage_nfs_home_dirs false
end
# Creates a group without users.
users_manage 'emptygroup' do
group_id 5000
action [:remove, :create]
end
users_manage 'explicituser' do
users node['users_test']['users']
end
users_manage 'spawns_next_group' do
users node['users_test']['users']
end
users_manage 'user_before_group' do
group_id 6000
users node['users_test']['users']
end
users_manage 'nonstandard_homedir_perms' do
users node['users_test']['users']
end
users_manage 'system_group' do
users node['users_test']['users']
system true
end
| ruby | Apache-2.0 | d62a03c765febf45464763207965ab7d6ac523ba | 2026-01-04T17:44:31.220288Z | false |
sous-chefs/users | https://github.com/sous-chefs/users/blob/d62a03c765febf45464763207965ab7d6ac523ba/test/fixtures/cookbooks/users_test/attributes/default.rb | test/fixtures/cookbooks/users_test/attributes/default.rb | default['users_test']['users'] = [{
'username': 'usertoremove',
'action': 'remove',
'groups': %w(nfsgroup),
'force': true,
'manage_home': true,
},
{
'id': 'databag_mwaddams',
'action': 'remove',
'groups': %w(testgroup nfsgroup),
'manage_home': true,
},
{
'id': 'user_with_dev_null_home',
'uid': 5000,
'gid': 4000,
'groups': ['nfsgroup'],
'primary_group': 'nfsgroup',
'shell': '/bin/bash',
'home': '/dev/null',
'no_user_group': true,
},
{
'id': 'user_with_nfs_home_first',
'groups': ['nfsgroup'],
'shell': '/bin/sh',
'ssh_public_key': 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIC6aZDF+x28xIlZSgyfyh3IAkencLp1VCU7JXBhJcXNy cheftestuser@laptop',
},
{
'id': 'user_with_nfs_home_second',
'groups': ['nfsgroup'],
'ssh_public_key': 'ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBCezwRzemhAGbqvvO/9RmiO9eOtRlUHn1HgvM4HDxxL/bFJCtUfyqbZfyQHXLqe7LJ0rRttAXWmcRLU/668bp70=',
'ssh_private_key': "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNlY2RzYS\n1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQQns8Ec3poQBm6r7zv/UZojvXjrUZVB\n59R4LzOBw8cS/2xSQrVH8qm2X8kB1y6nuyydK0bbQF1pnES1P+uvG6e9AAAAsD2Nf449jX\n+OAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBCezwRzemhAGbqvv\nO/9RmiO9eOtRlUHn1HgvM4HDxxL/bFJCtUfyqbZfyQHXLqe7LJ0rRttAXWmcRLU/668bp7\n0AAAAgJp/B6o2OADM0+NlkgH1dFcOLK64jhr3ScbWK4iyRdOcAAAAVZm11bGxlckBzYnBs\ndGMxbWxsdmRsAQID\n-----END OPENSSH PRIVATE KEY-----\n",
},
{
'id': 'user_with_local_home',
'groups': ['nfsgroup'],
'ssh_private_key': "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\nQyNTUxOQAAACAummQxfsdvMSJWUoMn8odyAJHp3C6dVQlOyVwYSXFzcgAAAJjzcJxA83Cc\nQAAAAAtzc2gtZWQyNTUxOQAAACAummQxfsdvMSJWUoMn8odyAJHp3C6dVQlOyVwYSXFzcg\nAAAEC7TGfA0MU0mh0V39qw5RSThUo0idTtU2vCe9bJrHmyFS6aZDF+x28xIlZSgyfyh3IA\nkencLp1VCU7JXBhJcXNyAAAAFWZtdWxsZXJAc2JwbHRjMW1sbHZkbA==\n-----END OPENSSH PRIVATE KEY-----\n",
},
{
'username': 'user_with_username_instead_of_id',
'groups': ['nfsgroup'],
'shell': '/bin/bash',
'ssh_keys': ['ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIC6aZDF+x28xIlZSgyfyh3IAkencLp1VCU7JXBhJcXNy cheftestuser@laptop'],
'ssh_private_key': "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\nQyNTUxOQAAACAummQxfsdvMSJWUoMn8odyAJHp3C6dVQlOyVwYSXFzcgAAAJjzcJxA83Cc\nQAAAAAtzc2gtZWQyNTUxOQAAACAummQxfsdvMSJWUoMn8odyAJHp3C6dVQlOyVwYSXFzcg\nAAAEC7TGfA0MU0mh0V39qw5RSThUo0idTtU2vCe9bJrHmyFS6aZDF+x28xIlZSgyfyh3IA\nkencLp1VCU7JXBhJcXNyAAAAFWZtdWxsZXJAc2JwbHRjMW1sbHZkbA==\n-----END OPENSSH PRIVATE KEY-----\n",
'ssh_public_key': 'ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBCezwRzemhAGbqvvO/9RmiO9eOtRlUHn1HgvM4HDxxL/bFJCtUfyqbZfyQHXLqe7LJ0rRttAXWmcRLU/668bp70=',
},
{
'username': 'explicituser',
'groups': ['explicituser'],
},
{
'username': 'joins_spawned_group',
'gid': 'string_gid',
'no_user_group': true,
'groups': ['user_before_group'],
},
{
'username': 'primary_integer_gid',
'groups': %w(spawns_next_group user_before_group),
'primary_group': 'user_before_group',
'gid': 6000,
},
{
'username': 'nonstandard_homedir_perms',
'homedir_mode': '02755',
'ssh_keys': ['ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIC6aZDF+x28xIlZSgyfyh3IAkencLp1VCU7JXBhJcXNy cheftestuser@laptop'],
'groups': ['nonstandard_homedir_perms'],
},
{
'id': 'system_user',
'groups': ['system_group'],
'system': true,
}]
| ruby | Apache-2.0 | d62a03c765febf45464763207965ab7d6ac523ba | 2026-01-04T17:44:31.220288Z | false |
sous-chefs/users | https://github.com/sous-chefs/users/blob/d62a03c765febf45464763207965ab7d6ac523ba/recipes/default.rb | recipes/default.rb | #
# Cookbook:: users
# Recipe:: default
#
# Copyright:: 2009-2019, Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
Chef::Log.warn('The default users recipe does nothing. See the readme for information on using the users resources')
| ruby | Apache-2.0 | d62a03c765febf45464763207965ab7d6ac523ba | 2026-01-04T17:44:31.220288Z | false |
sous-chefs/users | https://github.com/sous-chefs/users/blob/d62a03c765febf45464763207965ab7d6ac523ba/recipes/sysadmins.rb | recipes/sysadmins.rb | #
# Cookbook:: users
# Recipe:: sysadmins
#
# Copyright:: 2011-2017, Eric G. Wolfe
# Copyright:: 2009-2019, Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
Chef::Log.warn('The sysadmins recipe has been deprecated. We suggest using the users_manage resource in your own cookbook if you need similar functionality.')
| ruby | Apache-2.0 | d62a03c765febf45464763207965ab7d6ac523ba | 2026-01-04T17:44:31.220288Z | false |
sous-chefs/users | https://github.com/sous-chefs/users/blob/d62a03c765febf45464763207965ab7d6ac523ba/spec/manage_spec.rb | spec/manage_spec.rb | require 'chefspec'
users = [{
'id': 'test_user',
'uid': 9001,
'comment': 'Test User',
'password': '$1$5cE1rI/9$4p0fomh9U4kAI23qUlZVv/', # Do not do this in a production environment.
'shell': '/bin/bash',
'ssh_keys': 'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAklOUpkDHrfHY17SbrmTIpNLTGK9Tjom/BWDSU\nGPl+nafzlHDTYW7hdI4yZ5ew18JH4JW9jbhUFrviQzM7xlELEVf4h9lFX5QVkbPppSwg0cda3\nPbv7kOdJ/MTyBlWXFCR+HAo3FXRitBqxiX1nKhXpHAZsMciLq8V6RjsNAQwdsdMFvSlVK/7XA\nt3FaoJoAsncM1Q9x5+3V0Ww68/eIFmb1zuUFljQJKprrX88XypNDvjYNby6vw/Pb0rwert/En\nmZ+AW4OZPnTPI89ZPmVMLuayrD2cE86Z/il8b+gw3r3+1nKatmIkjn2so1d01QraTlMqVSsbx\nNrRFi9wrf+M7Q== chefuser@mylaptop.local',
'groups': %w(testgroup nfsgroup),
'manage_home': true,
},
{
'id': 'test_user_keys_from_url',
'password': '$1$5cE1rI/9$4p0fomh9U4kAI23qUlZVv/', # Do not do this in a production environment.
'uid': 9002,
'comment': 'Test User who grabs ssh keys from a url',
'shell': '/bin/bash',
'ssh_keys': [
'https://github.com/majormoses.keys',
'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAklOUpkDHrfHY17SbrmTIpNLTGK9Tjom/BWDSU\nGPl+nafzlHDTYW7hdI4yZ5ew18JH4JW9jbhUFrviQzM7xlELEVf4h9lFX5QVkbPppSwg0cda3\nPbv7kOdJ/MTyBlWXFCR+HAo3FXRitBqxiX1nKhXpHAZsMciLq8V6RjsNAQwdsdMFvSlVK/7XA\nt3FaoJoAsncM1Q9x5+3V0Ww68/eIFmb1zuUFljQJKprrX88XypNDvjYNby6vw/Pb0rwert/En\nmZ+AW4OZPnTPI89ZPmVMLuayrD2cE86Z/il8b+gw3r3+1nKatmIkjn2so1d01QraTlMqVSsbx\nNQCPO0ZZEa1== chefuser@mylaptop.local',
],
'groups': %w(testgroup nfsgroup),
},
{
'id': 'usertoremove',
'action': 'remove',
'groups': %w(testgroup),
'force': true,
'manage_home': true,
},
{
'id': 'bogus_user',
'action': 'remove',
'groups': %w(nfsgroup),
},
{
'id': 'user_with_dev_null_home',
'groups': ['testgroup'],
'shell': '/usr/bin/bash',
'home': '/dev/null',
},
{
'id': 'user_with_nfs_home_first',
'groups': ['testgroup'],
},
{
'id': 'user_with_nfs_home_second',
'groups': ['nfsgroup'],
},
{
'id': 'user_with_local_home',
'ssh_keys': ["ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAklOUpkDHrfHY17SbrmTIpNLTGK9Tjom/BWDSU\nGPl+nafzlHDTYW7hdI4yZ5ew18JH4JW9jbhUFrviQzM7xlELEVf4h9lFX5QVkbPppSwg0cda3\nPbv7kOdJ/MTyBlWXFCR+HAo3FXRitBqxiX1nKhXpHAZsMciLq8V6RjsNAQwdsdMFvSlVK/7XA\nt3FaoJoAsncM1Q9x5+3V0Ww68/eIFmb1zuUFljQJKprrX88XypNDvjYNby6vw/Pb0rwert/En\nmZ+AW4OZPnTPI89ZPmVMLuayrD2cE86Z/il8b+gw3r3+1nKatmIkjn2so1d01QraTlMqVSsbx\nNrRFi9wrf+M7Q== chefuser@mylaptop.local"],
'groups': ['testgroup'],
}]
describe 'users_manage' do
step_into :users_manage
platform 'ubuntu'
context 'running with "user_manage testgroup"' do
recipe do
users_manage 'testgroup' do
users users
group_id 3000
action [:remove, :create]
end
end
it 'creates groups' do
stub_command('getent group testgroup').and_return(false)
is_expected.to create_group('testgroup')
end
it 'creates users' do
stub_command('getent group testgroup').and_return(false)
is_expected.to create_user('user_with_dev_null_home')
is_expected.to create_user('user_with_local_home')
is_expected.to create_user('user_with_nfs_home_first')
end
it 'removes users' do
stub_command('getent group testgroup').and_return(false)
is_expected.to remove_user('usertoremove')
end
it 'not supports managing /dev/null home dir' do
stub_command('getent group testgroup').and_return(false)
is_expected.to create_user('user_with_dev_null_home')
.with(manage_home: false)
end
it 'supports managing local home dir' do
stub_command('getent group testgroup').and_return(false)
is_expected.to create_user('user_with_local_home')
.with(manage_home: true)
end
it 'not tries to manage .ssh dir for user "user_with_dev_null_home"' do
stub_command('getent group testgroup').and_return(false)
is_expected.to_not create_directory('/dev/null')
end
it 'manages .ssh dir for local user' do
stub_command('getent group testgroup').and_return(false)
is_expected.to create_directory('/home/user_with_local_home/.ssh')
end
it 'manages nfs home dir if manage_nfs_home_dirs is set to true' do
stub_command('getent group testgroup').and_return(false)
is_expected.to_not create_directory('/home/user_with_nfs_home_first/.ssh')
end
it 'does not manage nfs home dir if manage_nfs_home_dirs is set to false' do
stub_command('getent group testgroup').and_return(false)
is_expected.to_not create_directory('/home/user_with_nfs_home_second/.ssh')
end
it 'manages groups' do
stub_command('getent group testgroup').and_return(false)
is_expected.to create_users_manage('testgroup')
end
end
context 'running with "user_manage nfsgroup"' do
recipe do
users_manage 'nfsgroup' do
users users
group_id 4000
action [:remove, :create]
end
end
it 'creates groups' do
stub_command('getent group nfsgroup').and_return(false)
is_expected.to create_group('nfsgroup')
end
it 'creates users' do
stub_command('getent group nfsgroup').and_return(false)
is_expected.to create_user('user_with_nfs_home_second')
end
it 'removes users' do
stub_command('getent group nfsgroup').and_return(false)
is_expected.to remove_user('bogus_user')
end
it 'manages nfs home dir if manage_nfs_home_dirs is set to true' do
stub_command('getent group nfsgroup').and_return(false)
is_expected.to_not create_directory('/home/user_with_nfs_home_first/.ssh')
end
it 'does not manage nfs home dir if manage_nfs_home_dirs is set to false' do
stub_command('getent group nfsgroup').and_return(false)
is_expected.to_not create_directory('/home/user_with_nfs_home_second/.ssh')
end
it 'manages groups' do
stub_command('getent group nfsgroup').and_return(false)
is_expected.to create_users_manage('nfsgroup')
end
end
end
| ruby | Apache-2.0 | d62a03c765febf45464763207965ab7d6ac523ba | 2026-01-04T17:44:31.220288Z | false |
sous-chefs/users | https://github.com/sous-chefs/users/blob/d62a03c765febf45464763207965ab7d6ac523ba/spec/spec_helper.rb | spec/spec_helper.rb | require 'chefspec'
require 'chefspec/berkshelf'
RSpec.configure do |config|
config.color = true # Use color in STDOUT
config.formatter = :documentation # Use the specified formatter
config.log_level = :error # Avoid deprecation notice SPAM
end
| ruby | Apache-2.0 | d62a03c765febf45464763207965ab7d6ac523ba | 2026-01-04T17:44:31.220288Z | false |
sous-chefs/users | https://github.com/sous-chefs/users/blob/d62a03c765febf45464763207965ab7d6ac523ba/libraries/osx_helper.rb | libraries/osx_helper.rb | module Users
# Helpers for Users
module OsxHelper
def dscl(*args)
host = '.'
stdout_result = ''
stderr_result = ''
cmd = "dscl #{host} -#{args.join(' ')}"
status = shell_out(cmd)
status.stdout.each_line { |line| stdout_result << line }
status.stderr.each_line { |line| stderr_result << line }
[cmd, status, stdout_result, stderr_result]
end
def safe_dscl(*args)
result = dscl(*args)
return '' if (args.first =~ /^delete/) && (result[1].exitstatus != 0)
raise(Chef::Exceptions::Group, "dscl error: #{result.inspect}") unless result[1].exitstatus == 0
raise(Chef::Exceptions::Group, "dscl error: #{result.inspect}") if result[2] =~ /No such key: /
result[2]
end
def gid_used?(gid)
return false unless gid
groups_gids = safe_dscl('list /Groups gid')
!!(groups_gids =~ Regexp.new("#{Regexp.escape(gid.to_s)}\n"))
end
end
end
| ruby | Apache-2.0 | d62a03c765febf45464763207965ab7d6ac523ba | 2026-01-04T17:44:31.220288Z | false |
sous-chefs/users | https://github.com/sous-chefs/users/blob/d62a03c765febf45464763207965ab7d6ac523ba/libraries/helpers.rb | libraries/helpers.rb | module Users
# Helpers for Users
module Helpers
# Checks fs type.
#
# @return [String]
def fs_type(mount)
# Doesn't support macosx
stat = shell_out("stat -f -L -c %T #{mount} 2>&1")
stat.stdout.chomp
rescue
'none'
end
# Determines if provided mount point is remote.
#
# @return [Boolean]
def fs_remote?(mount)
fs_type(mount) == 'nfs'
end
def keys_from_url(url)
host = url.split('/')[0..2].join('/')
path = url.split('/')[3..-1].join('/')
begin
response = Chef::HTTP.new(host).get(path)
response.split("\n")
rescue Net::HTTPClientException => e
p "request: #{host}#{path}, error: #{e}"
end
end
# Determines if the user's shell is valid on the machine, otherwise
# returns the default of /bin/sh
#
# @return [String]
def shell_is_valid?(shell_path)
return false if shell_path.nil? || !File.exist?(shell_path)
# AIX is the only OS that has the concept of 'approved shells'
return true unless platform_family?('aix')
begin
File.open('/etc/security/login.cfg') do |f|
f.each_line do |l|
l.match(/^\s*shells\s*=\s*(.*)/) do |m|
return true if m[1].split(/\s*,\s*/).any? { |entry| entry.eql? shell_path }
end
end
end
rescue
return false
end
false
end
# Returns the appropriate base user home directory per platform
#
# @return [String]
def home_basedir
if platform_family?('mac_os_x')
'/Users'
elsif platform_family?('solaris2')
'/export/home'
else
'/home'
end
end
# Returns the type of the public key or rsa
#
# @return [String]
def pubkey_type(pubkey)
%w(ed25519 ecdsa dss rsa dsa).filter { |kt| pubkey.split.first.include?(kt) }.first || 'rsa'
end
# Returns a bool, deciding wether a username group must be created for a user
#
# @return [Bool]
def creates_user_group?(user)
!(platform_family?('suse', 'mac_os_x') || user[:no_user_group])
end
# Returns a bool, deciding wether a custom primary group must be created for a user
#
# @return [Bool]
def creates_primary_group?(user)
user[:gid] && !username_is_primary?(user) && !primary_gid(user).is_a?(Numeric)
end
# Returns a bool, deciding whether a users primary group is its username group based on their user hash
#
# @return [Bool]
def username_is_primary?(user)
if user[:gid]
user[:gid].is_a?(Numeric) && user[:primary_group].nil? && creates_user_group?(user)
else
creates_user_group?(user)
end
end
# Returns the name of a users primary group or an integer gid if a string isnt provided
# If a user hash contains an integer gid it defaults to the username group, assigning that gid.
# If a primary group is also passed than that group will be assigned the gid instead.
#
# @return [String, Integer]
def primary_gid(user)
if user[:gid].is_a?(Numeric)
user[:primary_group] || user[:gid].to_i
else
user[:gid]
end
end
# Returns the default user group based on os. On linux this group is the username group
#
# @return [String]
def get_default_group(user)
case node['platform_family']
when 'suse'
'users'
when 'mac_os_x'
'staff'
else
user[:username] || user[:id]
end
end
end
end
| ruby | Apache-2.0 | d62a03c765febf45464763207965ab7d6ac523ba | 2026-01-04T17:44:31.220288Z | false |
sous-chefs/users | https://github.com/sous-chefs/users/blob/d62a03c765febf45464763207965ab7d6ac523ba/resources/manage.rb | resources/manage.rb | #
# Cookbook:: users
# Resources:: manage
#
# Copyright:: 2011-2017, Eric G. Wolfe
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
unified_mode true
property :group_name, String, description: 'name of the group to create, defaults to resource name', name_property: true
property :group_id, Integer, description: 'numeric id of the group to create, default is to allow the OS to pick next.'
property :users, Array, description: 'Array of Hashes that contains all the users that you want to create with the users cookbook.', default: []
property :cookbook, String, description: 'name of the cookbook that the authorized_keys template should be found in.', default: 'users'
property :manage_nfs_home_dirs, [true, false], description: 'specifies if home_dirs should be managed when they are located on a NFS share.', default: true
property :system, [true, false], description: 'specifies if the group should be a system group. See the -r option of groupadd', default: false
# Deprecated properties
property :data_bag, String, deprecated: 'The data_bag property has been deprecated, please see upgrading.md for more information. The property will be removed in the next major release.'
action :create do
users_groups = {}
users_groups[new_resource.group_name] = []
# Create the group from the group property if it does not yet exist.
#
# The management of the members will be done in a seperate resource.
#
# Note that this is explicitly outside of the main user loop to accomodate
# https://github.com/sous-chefs/users/issues/450 .
group new_resource.group_name do
if platform_family?('mac_os_x')
gid new_resource.group_id unless gid_used?(new_resource.group_id)
not_if "dscl . list /Groups/#{new_resource.group_name}"
else
gid new_resource.group_id
not_if "getent group #{new_resource.group_name}"
end
system new_resource.system
end
# Loop through all the users in the users_hash
# Break the loop if users is not in the specified group_name
new_resource.users.each do |user|
next unless user[:groups].include?(new_resource.group_name)
next if user[:action] == 'remove'
username = user[:username] || user[:id]
user[:groups].each do |group|
users_groups[group] = [] unless users_groups.key?(group)
users_groups[group] << username
end
# Set home to location in data bag,
# or a reasonable default ($home_basedir/$user).
home_dir = user[:home] || "#{home_basedir}/#{username}"
# check whether home dir is null
manage_home = !(home_dir == '/dev/null')
# The user block will fail if its primary group doesn't exist.
# See the -g option limitations in man 8 useradd for an explanation.
# This section should correct that without breaking functionality.
# This creates a custom primary group if defined using the 'gid' and 'primary_group' keys
group primary_gid(user) do
if platform_family?('mac_os_x')
gid user[:gid].to_i unless gid_used?(user[:gid].to_i) || new_resource.group_name == username
else
gid user[:gid].to_i
end if user[:gid].is_a?(Numeric)
append true
end if creates_primary_group?(user)
# This creates a username group, it needs to be notified by another block so that it doesnt attempt to add a user
# that doesnt exist
group username do
if platform_family?('mac_os_x')
gid user[:gid].to_i unless gid_used?(user[:gid].to_i) || new_resource.group_name == username
else
gid user[:gid].to_i
end if user[:gid] && username_is_primary?(user)
members username unless username_is_primary?(user)
append true
action :nothing
end
# Create user object.
# Do NOT try to manage null home directories.
user username do
uid user[:uid].to_i unless platform_family?('mac_os_x') || !user[:uid]
if user[:gid] && !primary_gid(user).is_a?(Numeric)
gid primary_gid(user)
else
gid get_default_group(user)
end
shell shell_is_valid?(user[:shell]) ? user[:shell] : '/bin/sh'
comment user[:comment]
password user[:password] if user[:password]
salt user[:salt] if user[:salt]
iterations user[:iterations] if user[:iterations]
manage_home manage_home
home home_dir unless platform_family?('mac_os_x')
system user[:system] unless user[:system].nil?
action :create
if username_is_primary?(user)
notifies :create, "group[#{username}]", :before
elsif creates_user_group?(user)
notifies :create, "group[#{username}]", :immediately
end
end
if manage_home_files?(home_dir, username)
Chef::Log.debug("Managing home files for #{username}")
directory home_dir do
mode user[:homedir_mode]
end if user[:homedir_mode]
directory "#{home_dir}/.ssh" do
recursive true
owner user[:uid] ? user[:uid].to_i : username
if user[:gid] && !primary_gid(user).is_a?(Numeric)
group primary_gid(user)
else
group get_default_group(user)
end
mode '0700'
not_if { user[:ssh_keys].nil? && user[:ssh_private_key].nil? && user[:ssh_public_key].nil? }
end
# loop over the keys and if we have a URL we should add each key
# from the url response and append it to the list of keys
ssh_keys = []
Array(user[:ssh_keys]).each do |key|
if key.start_with?('https')
ssh_keys += keys_from_url(key)
else
ssh_keys << key
end
end
# use the keyfile defined in the databag or fallback to the standard file in the home dir
key_file = user[:authorized_keys_file] || "#{home_dir}/.ssh/authorized_keys"
template key_file do
source 'authorized_keys.erb'
cookbook new_resource.cookbook
owner user[:uid] ? user[:uid].to_i : username
if user[:gid] && !primary_gid(user).is_a?(Numeric)
group primary_gid(user)
else
group get_default_group(user)
end
mode '0600'
sensitive true
# ssh_keys should be a combination of user['ssh_keys'] and any keys
# returned from a specified URL
variables ssh_keys: ssh_keys
not_if { user[:ssh_keys].nil? }
end
if user[:ssh_public_key]
pubkey_type = pubkey_type(user[:ssh_public_key])
template "#{home_dir}/.ssh/id_#{pubkey_type}.pub" do
source 'public_key.pub.erb'
cookbook new_resource.cookbook
owner user[:uid] ? user[:uid].to_i : username
if user[:gid] && !primary_gid(user).is_a?(Numeric)
group primary_gid(user)
else
group get_default_group(user)
end
mode '0400'
variables public_key: user[:ssh_public_key]
end
end
if user[:ssh_private_key]
key_type = pubkey_type || 'rsa'
template "#{home_dir}/.ssh/id_#{key_type}" do
source 'private_key.erb'
cookbook new_resource.cookbook
owner user[:uid] ? user[:uid].to_i : username
if user[:gid] && !primary_gid(user).is_a?(Numeric)
group primary_gid(user)
else
group get_default_group(user)
end
mode '0400'
variables private_key: user[:ssh_private_key]
end
end
else
Chef::Log.debug("Not managing home files for #{username}")
end
end
# Populating users to appropriates groups
users_groups.each do |group, user|
group group do
members user
append true
action :manage # Do nothing if group doesn't exist
end
end
end
action :remove do
new_resource.users.each do |user|
next unless (user[:groups].include? new_resource.group_name) && (user[:action] == 'remove' unless user[:action].nil?)
user user[:username] || user[:id] do
action :remove
manage_home user[:manage_home] || false
force user[:force] || false
end
end
end
action_class do
include ::Users::Helpers
include ::Users::OsxHelper
def manage_home_files?(home_dir, _user)
# Don't manage home dir if it's NFS mount
# and manage_nfs_home_dirs is disabled
if home_dir == '/dev/null'
false
elsif fs_remote?(home_dir)
new_resource.manage_nfs_home_dirs ? true : false
else
true
end
end
end
| ruby | Apache-2.0 | d62a03c765febf45464763207965ab7d6ac523ba | 2026-01-04T17:44:31.220288Z | false |
jollygoodcode/twemoji | https://github.com/jollygoodcode/twemoji/blob/eecb84f7f2318b5239c5cd72c5323ec7056275f1/test/twemoji_test.rb | test/twemoji_test.rb | require "test_helper"
class TwemojiTest < Minitest::Test
def setup
end
def test_number_of_emojis
assert_equal 1661, Twemoji.codes.size
end
def test_twemoji_png_and_svg_not_loaded_by_default
assert_raises NameError do
Twemoji::PNG
Twemoji::SVG
end
end
def test_twemoji_png
require "twemoji/png"
assert_raises NameError do
Twemoji::PNG
end
assert_equal 1661, Twemoji.png.size
end
def test_twemoji_svg
require "twemoji/svg"
assert_raises NameError do
Twemoji::SVG
end
assert_equal 1661, Twemoji.svg.size
end
def test_finder_methods_cannot_find_by_more_than_one
exception = assert_raises ArgumentError do
Twemoji.find_by(text: ":heart_eyes:", code: "1f60d")
end
assert_equal "Can only specify text, code or unicode one at a time", exception.message
end
def test_finder_methods_find_by_text
assert_equal "1f60d", Twemoji.find_by(text: ":heart_eyes:")
end
def test_finder_methods_find_by_code
assert_equal ":heart_eyes:", Twemoji.find_by(code: "1f60d")
end
def test_finder_methods_find_by_unicode
assert_equal ":heart_eyes:", Twemoji.find_by(unicode: "😍")
end
def test_find_by_text
assert_equal "1f60d", Twemoji.find_by_text(":heart_eyes:")
end
def test_find_by_code
assert_equal ":heart_eyes:", Twemoji.find_by_code("1f60d")
end
def test_find_by_unicode
assert_equal ":heart_eyes:", Twemoji.find_by_unicode("😍")
end
def test_find_by_unicode_copyright
assert_equal ":copyright:", Twemoji.find_by_unicode("©")
end
def test_find_by_unicode_country_flag
assert_equal ":flag-es:", Twemoji.find_by_unicode("🇪🇸")
end
def test_render_unicode_country_flag_es
assert_equal "🇪🇸", Twemoji.render_unicode(":flag-es:")
end
def test_render_unicode_country_flag_es_unicode
assert_equal "🇪🇸", Twemoji.render_unicode("1f1ea-1f1f8")
end
def test_find_by_escaped_unicode
assert_equal ":heart_eyes:", Twemoji.find_by_unicode("\u{1f60d}")
end
def test_parse_plus_one
expected = %(<img draggable="false" title=":+1:" alt="👍" src="https://twemoji.maxcdn.com/2/svg/1f44d.svg" class="emoji">)
assert_equal expected, Twemoji.parse(":+1:")
end
def test_parse_minus_one
expected = %(<img draggable="false" title=":-1:" alt="👎" src="https://twemoji.maxcdn.com/2/svg/1f44e.svg" class="emoji">)
assert_equal expected, Twemoji.parse(":-1:")
end
def test_parse_html_string
expected = %(I like chocolate <img draggable="false" title=":heart_eyes:" alt="😍" src="https://twemoji.maxcdn.com/2/svg/1f60d.svg" class="emoji">!)
assert_equal expected, Twemoji.parse("I like chocolate :heart_eyes:!")
end
def test_parse_document
doc = Nokogiri::HTML::DocumentFragment.parse("<p>I like chocolate :heart_eyes:!</p>")
expected = '<p>I like chocolate <img draggable="false" title=":heart_eyes:" alt="😍" src="https://twemoji.maxcdn.com/2/svg/1f60d.svg" class="emoji">!</p>'
assert_equal expected, Twemoji.parse(doc).to_html
end
def test_parse_option_asset_root
expected = %(I like chocolate <img draggable="false" title=":heart_eyes:" alt="😍" src="https://emoji.bestcdn.com/svg/1f60d.svg" class="emoji">!)
assert_equal expected, Twemoji.parse("I like chocolate :heart_eyes:!", asset_root: 'https://emoji.bestcdn.com')
end
def test_parse_option_file_ext_png
expected = %(I like chocolate <img draggable="false" title=":heart_eyes:" alt="😍" src="https://twemoji.maxcdn.com/2/72x72/1f60d.png" class="emoji">!)
assert_equal expected, Twemoji.parse("I like chocolate :heart_eyes:!", file_ext: 'png')
end
def test_parse_option_unsupport_file_ext_gif
exception = assert_raises RuntimeError do
Twemoji.parse("I like chocolate :heart_eyes:!", file_ext: 'gif')
end
assert_equal "Unsupported file extension: gif", exception.message
end
def test_parse_option_class_name
expected = %(I like chocolate <img draggable="false" title=":heart_eyes:" alt="😍" src="https://twemoji.maxcdn.com/2/svg/1f60d.svg" class="twemoji">!)
assert_equal expected, Twemoji.parse("I like chocolate :heart_eyes:!", class_name: 'twemoji')
end
def test_parse_option_single_img_attr
expected = %(I like chocolate <img draggable="false" title=":heart_eyes:" alt="😍" src="https://twemoji.maxcdn.com/2/svg/1f60d.svg" class="twemoji" style="height: 1.3em;">!)
assert_equal expected, Twemoji.parse("I like chocolate :heart_eyes:!", class_name: 'twemoji', img_attrs: { style: 'height: 1.3em;' })
end
def test_parse_option_multiple_img_attrs
expected = %(I like chocolate <img draggable="false" title=":heart_eyes:" alt="😍" src="https://twemoji.maxcdn.com/2/svg/1f60d.svg" class="twemoji" style="height: 1.3em;" width="20">!)
assert_equal expected, Twemoji.parse("I like chocolate :heart_eyes:!", class_name: 'twemoji', img_attrs: { style: 'height: 1.3em;', width: "20" })
end
def test_parse_option_img_attr_callable
shortname_filter = ->(name) { name.gsub(":", "") }
img_attrs = {
style: "height: 1.3em;",
title: shortname_filter,
alt: shortname_filter,
}
expected = %(I like chocolate <img draggable="false" title="heart_eyes" alt="heart_eyes" src="https://twemoji.maxcdn.com/2/svg/1f60d.svg" class="twemoji" style="height: 1.3em;">!)
assert_equal expected, Twemoji.parse("I like chocolate :heart_eyes:!", class_name: 'twemoji', img_attrs: img_attrs)
end
def test_parse_diversity_emojis
DiversityEmoji.all.each do |diversity|
# Each diversity set of emojis (base + 5 modifier = 6) should result in 6 img tags
assert_equal 6, Twemoji.parse(diversity).scan(/<img/).size
end
end
def test_parse_flag_img_alt
expected = %(<img draggable=\"false\" title=\":flag-sg:\" alt=\"🇸🇬\" src=\"https://twemoji.maxcdn.com/2/svg/1f1f8-1f1ec.svg\" class=\"emoji\">)
assert_equal expected, Twemoji.parse(":flag-sg:")
end
def test_emoji_pattern
assert_kind_of Regexp, Twemoji.emoji_pattern
end
def test_emoji_unicode
assert_kind_of Regexp, Twemoji.emoji_pattern_unicode
end
def test_emoji_all
assert_kind_of Regexp, Twemoji.emoji_pattern_all
end
def test_parse_by_unicode
expected = %(<img draggable="false" title=":heart_eyes:" alt="😍" src="https://twemoji.maxcdn.com/2/svg/1f60d.svg" class="emoji">)
assert_equal expected, Twemoji.parse("😍")
end
def test_parse_by_unicode_flag
expected = %(<img draggable=\"false\" title=\":flag-my:\" alt=\"🇲🇾\" src=\"https://twemoji.maxcdn.com/2/svg/1f1f2-1f1fe.svg\" class=\"emoji\">)
assert_equal expected, Twemoji.parse("🇲🇾")
end
def test_parse_by_unicode_text
expected = %(I like chocolate <img draggable="false" title=":heart_eyes:" alt="😍" src="https://twemoji.maxcdn.com/2/svg/1f60d.svg" class="twemoji">!)
assert_equal expected, Twemoji.parse("I like chocolate 😍!", class_name: 'twemoji')
end
def test_parse_by_unicode_attr
expected = %(<img draggable="false" title=":heart_eyes:" alt="😍" src="https://twemoji.maxcdn.com/2/svg/1f60d.svg" class="twemoji" aria-label="emoji: heart_eyes">)
aria_label = ->(name) { 'emoji: ' + name.gsub(":", '') }
assert_equal expected, Twemoji.parse("😍", img_attrs: {'aria-label'=> aria_label }, class_name: 'twemoji' )
end
def test_parse_by_unicode_multiple
expected = %(<img draggable="false" title=":cookie:" alt="🍪" src="https://twemoji.maxcdn.com/2/svg/1f36a.svg" class="emoji" aria-label="emoji: cookie"><img draggable="false" title=":birthday:" alt="🎂" src="https://twemoji.maxcdn.com/2/svg/1f382.svg" class="emoji" aria-label="emoji: birthday">)
aria_label = ->(name) { 'emoji: ' + name.gsub(":", '') }
assert_equal expected, Twemoji.parse("🍪🎂", img_attrs: {'aria-label'=> aria_label } )
end
def test_parse_by_unicode_multiple_html
expected = %(<p><img draggable="false" title=":cookie:" alt="🍪" src="https://twemoji.maxcdn.com/2/svg/1f36a.svg" class="emoji" aria-label="emoji: cookie"><img draggable="false" title=":birthday:" alt="🎂" src="https://twemoji.maxcdn.com/2/svg/1f382.svg" class="emoji" aria-label="emoji: birthday"></p>)
aria_label = ->(name) { 'emoji: ' + name.gsub(":", '') }
assert_equal expected, Twemoji.parse(Nokogiri::HTML::DocumentFragment.parse("<p>🍪🎂</p>"), img_attrs: {'aria-label'=> aria_label } ).to_html
end
def test_parse_by_unicode_multiple_mix_codepoint_name_html
expected = %(<p><img draggable="false" title=":cookie:" alt="🍪" src="https://twemoji.maxcdn.com/2/svg/1f36a.svg" class="emoji" aria-label="emoji: cookie"><img draggable="false" title=":birthday:" alt="🎂" src="https://twemoji.maxcdn.com/2/svg/1f382.svg" class="emoji" aria-label="emoji: birthday"></p>)
aria_label = ->(name) { 'emoji: ' + name.gsub(":", '') }
assert_equal expected, Twemoji.parse(Nokogiri::HTML::DocumentFragment.parse("<p>🍪:birthday:</p>"), img_attrs: {'aria-label'=> aria_label } ).to_html
end
def test_parse_by_unicode_and_name
expected = %(<img draggable="false" title=":cookie:" alt="🍪" src="https://twemoji.maxcdn.com/2/svg/1f36a.svg" class="emoji" aria-label="emoji: cookie"><img draggable="false" title=":birthday:" alt="🎂" src="https://twemoji.maxcdn.com/2/svg/1f382.svg" class="emoji" aria-label="emoji: birthday">)
aria_label = ->(name) { 'emoji: ' + name.gsub(":", '') }
assert_equal expected, Twemoji.parse(":cookie:🎂", img_attrs: {'aria-label'=> aria_label } )
end
def test_parse_multiple
expected = %(<img draggable="false" title=":cookie:" alt="🍪" src="https://twemoji.maxcdn.com/2/svg/1f36a.svg" class="emoji" aria-label="emoji: cookie"><img draggable="false" title=":birthday:" alt="🎂" src="https://twemoji.maxcdn.com/2/svg/1f382.svg" class="emoji" aria-label="emoji: birthday">)
aria_label = ->(name) { 'emoji: ' + name.gsub(":", '') }
assert_equal expected, Twemoji.parse(":cookie::birthday:", img_attrs: {'aria-label'=> aria_label } )
end
def test_parse_empty_class_name
expected = '<img draggable="false" title=":flag-br:" alt="🇧🇷" src="https://twemoji.maxcdn.com/2/svg/1f1e7-1f1f7.svg">'
assert_equal expected, Twemoji.parse('🇧🇷', class_name: nil)
assert_equal expected, Twemoji.parse('🇧🇷', class_name: '')
end
end
| ruby | MIT | eecb84f7f2318b5239c5cd72c5323ec7056275f1 | 2026-01-04T17:44:35.040581Z | false |
jollygoodcode/twemoji | https://github.com/jollygoodcode/twemoji/blob/eecb84f7f2318b5239c5cd72c5323ec7056275f1/test/test_helper.rb | test/test_helper.rb | # frozen_string_literal: true
require "bundler/setup"
require "twemoji"
require "minitest/autorun"
module Twemoji
module TestExtensions
def assert_nothing_raised
yield if block_given?
end
class DiversityEmoji
def self.all
BASES.map { |base| diversitify(base) }
end
BASES = %w(
:santa: :snowboarder: :runner: :surfer: :horse_racing: :swimmer: :weight_lifter: :ear:
:nose: :point_up_2: :point_down: :point_left: :point_right: :facepunch: :wave: :ok_hand:
:+1: :-1: :clap: :open_hands: :boy: :girl: :man: :woman: :cop: :bride_with_veil:
:person_with_blond_hair: :man_with_gua_pi_mao: :man_with_turban: :older_man: :older_woman:
:baby: :construction_worker: :princess: :angel: :information_desk_person: :guardsman:
:dancer: :nail_care: :massage: :haircut: :muscle: :sleuth_or_spy:
:raised_hand_with_fingers_splayed: :middle_finger: :spock-hand: :no_good: :ok_woman: :bow:
:raising_hand: :raised_hands: :person_frowning: :person_with_pouting_face: :pray: :rowboat:
:bicyclist: :mountain_bicyclist: :walking: :bath: :the_horns: :point_up: :person_with_ball:
:fist: :hand: :victory_hand: :writing_hand:
)
private_constant :BASES
def self.diversitify(base)
"#{base} #{base}:skin-tone-2: #{base}:skin-tone-3: #{base}:skin-tone-4: #{base}:skin-tone-5: #{base}:skin-tone-6:"
end
private_class_method :diversitify
end
end
end
class Minitest::Test
include Twemoji::TestExtensions
end
| ruby | MIT | eecb84f7f2318b5239c5cd72c5323ec7056275f1 | 2026-01-04T17:44:35.040581Z | false |
jollygoodcode/twemoji | https://github.com/jollygoodcode/twemoji/blob/eecb84f7f2318b5239c5cd72c5323ec7056275f1/test/configuration_test.rb | test/configuration_test.rb | require "test_helper"
class TwemojiConfigurationTest < Minitest::Test
def teardown
Twemoji.configuration = nil
Twemoji.configure {}
end
def test_configuration_defaults
assert_equal "https://twemoji.maxcdn.com/2", Twemoji.configuration.asset_root
assert_equal "svg", Twemoji.configuration.file_ext
assert_equal "emoji", Twemoji.configuration.class_name
assert_equal Hash(nil), Twemoji.configuration.img_attrs
end
def test_configuration_asset_root
Twemoji.configure do |config|
config.asset_root = "https://twemoji.awesomecdn.com/"
end
assert_equal "https://twemoji.awesomecdn.com/", Twemoji.configuration.asset_root
end
def test_configuration_file_ext
Twemoji.configure do |config|
config.file_ext = "png"
end
assert_equal "png", Twemoji.configuration.file_ext
end
def test_configuration_class_name
Twemoji.configure do |config|
config.class_name = "twemoji"
end
assert_equal "twemoji", Twemoji.configuration.class_name
end
def test_configuration_img_attrs
Twemoji.configure do |config|
config.img_attrs = { style: "height: 1.3em" }
end
assert_equal Hash(style: "height: 1.3em"), Twemoji.configuration.img_attrs
end
end
| ruby | MIT | eecb84f7f2318b5239c5cd72c5323ec7056275f1 | 2026-01-04T17:44:35.040581Z | false |
jollygoodcode/twemoji | https://github.com/jollygoodcode/twemoji/blob/eecb84f7f2318b5239c5cd72c5323ec7056275f1/test/utils/unicode_test.rb | test/utils/unicode_test.rb | require "test_helper"
module Twemoji
module Utils
class UnicodeTest < Minitest::Test
def test_unpack
result = Twemoji::Utils::Unicode.unpack("🇲🇾")
assert_equal "1f1f2-1f1fe", result
end
end
end
end
| ruby | MIT | eecb84f7f2318b5239c5cd72c5323ec7056275f1 | 2026-01-04T17:44:35.040581Z | false |
jollygoodcode/twemoji | https://github.com/jollygoodcode/twemoji/blob/eecb84f7f2318b5239c5cd72c5323ec7056275f1/lib/twemoji.rb | lib/twemoji.rb | # frozen_string_literal: true
require "nokogiri"
require "json"
require "twemoji/version"
require "twemoji/map"
require "twemoji/configuration"
require "twemoji/utils/unicode"
# Twemoji is a Ruby implementation, parses your text, replace emoji text
# with corresponding emoji image. Default emoji images are from Twiiter CDN.
module Twemoji
# Find code by text, find text by code, and find text by unicode.
#
# @example Usage
# Twemoji.find_by(text: ":heart_eyes:") # => "1f60d"
# Twemoji.find_by(code: "1f60d") # => ":heart_eyes:"
# Twemoji.find_by(unicode: "😍") # => ":heart_eyes:"
# Twemoji.find_by(unicode: "\u{1f60d}") # => ":heart_eyes:"
#
# @option options [String] (optional) :text
# @option options [String] (optional) :code
# @option options [String] (optional) :unicode
#
# @return [String] Emoji text or code.
def self.find_by(text: nil, code: nil, unicode: nil)
if [ text, code, unicode ].compact!.size > 1
fail ArgumentError, "Can only specify text, code or unicode one at a time"
end
case
when text
find_by_text text
when unicode
find_by_unicode unicode
else
find_by_code code
end
end
# Find emoji code by emoji text.
#
# @example Usage
# Twemoji.find_by_text ":heart_eyes:"
# => "1f60d"
#
# @param text [String] Text to find emoji code.
# @return [String] Emoji Code.
def self.find_by_text(text)
codes[must_str(text)]
end
# Find emoji text by emoji code.
#
# @example Usage
# Twemoji.find_by_code "1f60d"
# => ":heart_eyes:"
#
# @param code [String] Emoji code to find text.
# @return [String] Emoji Text.
def self.find_by_code(code)
invert_codes[must_str(code)]
end
# Find emoji text by raw emoji unicode.
#
# @example Usage
# Twemoji.find_by_unicode "😍"
# => ":heart_eyes:"
#
# @param raw [String] Emoji raw unicode to find text.
# @return [String] Emoji Text.
def self.find_by_unicode(raw)
invert_codes[unicode_to_str(raw)]
end
# Render raw emoji unicode from emoji text or emoji code.
#
# @example Usage
# Twemoji.render_unicode ":heart_eyes:"
# => "😍"
# Twemoji.render_unicode "1f60d"
# => "😍"
#
# @param text_or_code [String] Emoji text or code to render as unicode.
# @return [String] Emoji UTF-8 Text.
def self.render_unicode(text_or_code)
text_or_code = find_by_text(text_or_code) if text_or_code[0] == ?:
unicodes = text_or_code.split(?-)
unicodes.map(&:hex).pack(?U*unicodes.size)
end
# Parse string, replace emoji text with image.
# Parse DOM, replace emoji with image.
#
# @example Usage
# Twemoji.parse("I like chocolate :heart_eyes:!")
# => 'I like chocolate <img draggable="false" title=":heart_eyes:" alt="😍" src="https://twemoji.maxcdn.com/2/svg/1f60d.svg" class="emoji">!'
#
# @param text [String] Source text to parse.
#
# @option options [String] (optional) asset_root Asset root url to serve emoji.
# @option options [String] (optional) file_ext File extension.
# @option options [String] (optional) class_name Emoji image's tag class attribute.
# @option options [String] (optional) img_attrs Emoji image's img tag attributes.
#
# @return [String] Original text with all occurrences of emoji text
# replaced by emoji image according to given options.
def self.parse(text, asset_root: Twemoji.configuration.asset_root,
file_ext: Twemoji.configuration.file_ext,
class_name: Twemoji.configuration.class_name,
img_attrs: Twemoji.configuration.img_attrs)
options[:asset_root] = asset_root
options[:file_ext] = file_ext
options[:img_attrs] = { class: class_name }.merge(img_attrs)
if text.is_a?(Nokogiri::HTML::DocumentFragment)
parse_document(text)
else
parse_html(text)
end
end
# Return all emoji patterns' regular expressions.
#
# @return [RegExp] A Regular expression consists of all emojis text.
def self.emoji_pattern
EMOJI_PATTERN
end
# Return all emoji patterns' regular expressions in unicode.
# e.g '1f1f2-1f1fe' will be converted to \u{1f1f2}\u{1f1fe} for RegExp matching.
#
# @return [RegExp] A Regular expression consists of all emojis unicode.
def self.emoji_pattern_unicode
EMOJI_PATTERN_UNICODE
end
# Return all emoji patterns' regular expressions in unicode and name.
#
# @return [RegExp] A Regular expression consists of all emojis unicode codepoint and names.
def self.emoji_pattern_all
EMOJI_PATTERN_ALL
end
private
# Return sorted codepoint values by descending length.
#
# @return [Array] An array of emoji codepoint values sorted by descending length
def self.sorted_codepoint_values
# has to be sorted to match the combined codepoint (2-3 char emojis) before single char emojis
@sorted_codepoint_values ||= invert_codes.keys.sort_by {|key| key.length }.reverse
end
EMOJI_PATTERN = /#{codes.keys.map { |name| Regexp.quote(name) }.join("|")}/.freeze
EMOJI_PATTERN_UNICODE = /#{sorted_codepoint_values.map { |name| Regexp.quote(name.split('-').collect {|n| n.hex}.pack("U*")) }.join("|")}/.freeze
EMOJI_PATTERN_ALL = /(#{EMOJI_PATTERN}|#{EMOJI_PATTERN_UNICODE})/.freeze
private_constant :EMOJI_PATTERN, :EMOJI_PATTERN_UNICODE, :EMOJI_PATTERN_ALL
# Ensure text is a string.
#
# @param text [String] Text to ensure to be a string.
# @return [String] A String.
# @private
def self.must_str(text)
text.respond_to?(:to_str) ? text.to_str : text.to_s
end
# Options hash for Twemoji.
#
# @return [Hash] Hash of options.
# @private
def self.options
@options ||= {}
end
# Parse a HTML String, replace emoji text with corresponding emoji image.
#
# @param text [String] Text string to be parse.
# @param filter [Symbol] Symbol of filter function to use. Available filters
# are :filter_emoji and :filter_emoji_unicode.
# @return [String] Text with emoji text replaced by emoji image.
# @private
def self.parse_html(text, filter = :filter_emojis)
self.send(filter, text)
end
# Parse a Nokogiri::HTML::DocumentFragment document, replace emoji text
# with corresponding emoji image.
#
# @param doc [Nokogiri::HTML::DocumentFragment] Document to parse.
# @param filter [Symbol] Symbol of filter function to use. Available filters
# are :filter_emoji and :filter_emoji_unicode.
# @return [Nokogiri::HTML::DocumentFragment] Parsed document.
# @private
def self.parse_document(doc, filter = :filter_emojis)
doc.xpath(".//text() | text()").each do |node|
content = node.to_html
next if has_ancestor?(node, %w(pre code tt))
html = self.send(filter, content)
next if html == content
node.replace(html)
end
doc
end
# Find out if a node with given exclude tags has ancestors.
#
# @param node [Nokogiri::XML::Text] Text node to find ancestor.
# @param tags [Array] Array of String represents tags.
# @return [Boolean] If has ancestor returns true, otherwise falsy (nil).
# @private
def self.has_ancestor?(node, tags)
while node = node.parent
if tags.include?(node.name.downcase)
break true
end
end
end
# Filter emoji text in content, replaced by corresponding emoji image.
#
# @param content [String] Content to filter emoji text to image.
# @return [String] Returns a String just like content with all emoji text
# replaced by the corresponding emoji image.
# @private
def self.filter_emojis(content, pattern = emoji_pattern_all)
content.gsub(pattern) { |match| img_tag(match) }
end
# Returns emoji image tag by given name and options from `Twemoji.parse`.
#
# @param name [String] Emoji name to generate image tag.
# @return [String] Emoji image tag generated by name and options.
# @private
def self.img_tag(name)
# choose default attributes based on name or unicode codepoint
default_attrs = name.include?(":") ? default_attrs(name) : default_attrs_unicode(name)
text_name = name.include?(":") ? name : find_by_unicode(name)
img_attrs_hash = default_attrs.merge! customized_attrs(text_name)
%(<img #{hash_to_html_attrs(img_attrs_hash)}>)
end
PNG_IMAGE_SIZE = "72x72"
private_constant :PNG_IMAGE_SIZE
# Returns emoji url by given name and options from `Twemoji.parse`.
#
# @param name [String] Emoji name to generate image url.
# @return [String] Emoji image tag generated by name and options.
# @private
def self.emoji_url(name, finder = :find_by_text)
code = self.send(finder, name)
if options[:file_ext] == "png"
File.join(options[:asset_root], PNG_IMAGE_SIZE, "#{code}.png")
elsif options[:file_ext] == "svg"
File.join(options[:asset_root], "svg", "#{code}.svg")
else
fail "Unsupported file extension: #{options[:file_ext]}"
end
end
# Returns user customized img attributes. If attribute value is any proc-like
# object, will call it and the emoji name will be passed as argument.
#
# @param name [String] Emoji name.
# @return Hash of customized attributes
# @private
def self.customized_attrs(name)
custom_img_attributes = {}
options[:img_attrs].each do |key, value|
# run value filters where given
if value.respond_to?(:call)
custom_img_attributes[key] = value.call(name)
else
custom_img_attributes[key] = value
end
end
custom_img_attributes
end
# Default img attributes: draggable, title, alt, src.
#
# @param name [String] Emoji name.
# @return Hash of default attributes
# @private
def self.default_attrs(name)
{
draggable: "false".freeze,
title: name,
alt: render_unicode(name),
src: emoji_url(name)
}
end
# Default img attributes for unicode: draggable, title, alt, src.
#
# @param unicode [String] Emoji unicode codepoint.
# @return Hash of default attributes
# @private
def self.default_attrs_unicode(unicode)
{
draggable: "false".freeze,
title: find_by_unicode(unicode),
alt: unicode,
src: emoji_url(unicode, :unicode_to_str)
}
end
# Convert raw unicode to string key version.
#
# e.g. 🇲🇾 converts to "1f1f2-1f1fe"
# @param unicode [String] Unicode codepoint.
# @return String representation of unicode codepoint
# @private
def self.unicode_to_str(unicode)
Twemoji::Utils::Unicode.unpack(unicode)
end
# Coverts hash of attributes into HTML attributes.
#
# @param hash [Hash] Hash of attributes.
# @return [String] HTML attributes suitable for use in tag
# @private
def self.hash_to_html_attrs(hash)
hash.reject { |key, value| value.nil? || value == '' }.map { |attr, value| %(#{attr}="#{value}") }.join(" ")
end
end
| ruby | MIT | eecb84f7f2318b5239c5cd72c5323ec7056275f1 | 2026-01-04T17:44:35.040581Z | false |
jollygoodcode/twemoji | https://github.com/jollygoodcode/twemoji/blob/eecb84f7f2318b5239c5cd72c5323ec7056275f1/lib/twemoji/version.rb | lib/twemoji/version.rb | # frozen_string_literal: true
module Twemoji
VERSION = "3.1.8"
end
| ruby | MIT | eecb84f7f2318b5239c5cd72c5323ec7056275f1 | 2026-01-04T17:44:35.040581Z | false |
jollygoodcode/twemoji | https://github.com/jollygoodcode/twemoji/blob/eecb84f7f2318b5239c5cd72c5323ec7056275f1/lib/twemoji/svg.rb | lib/twemoji/svg.rb | # frozen_string_literal: true
module Twemoji
def self.svg
SVG
end
SVG = Twemoji.load_yaml(Configuration::SVG_MAP_FILE).freeze
private_constant :SVG
end
| ruby | MIT | eecb84f7f2318b5239c5cd72c5323ec7056275f1 | 2026-01-04T17:44:35.040581Z | false |
jollygoodcode/twemoji | https://github.com/jollygoodcode/twemoji/blob/eecb84f7f2318b5239c5cd72c5323ec7056275f1/lib/twemoji/configuration.rb | lib/twemoji/configuration.rb | # frozen_string_literal: true
require "yaml"
module Twemoji
def self.configuration
@configuration ||= Configuration.new
end
def self.configuration=(configuration)
@configuration = configuration
end
def self.configure
yield configuration
end
def self.load_yaml(path)
YAML.safe_load(IO.read(path))
end
class Configuration
DATA_DIR = File.join(File.dirname(__FILE__), "data")
CODE_MAP_FILE = File.join(DATA_DIR, "emoji-unicode.yml")
PNG_MAP_FILE = File.join(DATA_DIR, "emoji-unicode-png.yml")
SVG_MAP_FILE = File.join(DATA_DIR, "emoji-unicode-svg.yml")
attr_accessor :asset_root, :file_ext, :class_name, :img_attrs
def initialize
@asset_root = "https://twemoji.maxcdn.com/2"
@file_ext = "svg"
@class_name = "emoji"
@img_attrs = {}
end
end
end
| ruby | MIT | eecb84f7f2318b5239c5cd72c5323ec7056275f1 | 2026-01-04T17:44:35.040581Z | false |
jollygoodcode/twemoji | https://github.com/jollygoodcode/twemoji/blob/eecb84f7f2318b5239c5cd72c5323ec7056275f1/lib/twemoji/map.rb | lib/twemoji/map.rb | # frozen_string_literal: true
require "twemoji/configuration"
module Twemoji
# Emoji Text to Codepoint mappings.
#
# @example Usage
# codes[":heart_eyes:"] # => "1f60d"
# codes[":notebook_with_decorative_cover:"] # => "1f4d4"
# @return [Hash<String => String>]
def self.codes
CODES
end
# Emoji Codepoint to Text mappings. This hash is frozen.
#
# @example Usage
# invert_codes["1f60d"] # => ":heart_eyes:"
# invert_codes["1f4d4"] # => ":notebook_with_decorative_cover:"
#
# @return [Hash<String => String>]
def self.invert_codes
codes.invert.freeze
end
# Emoji Text to Codepoint mapping constant. This hash is frozen.
# @private
CODES = Twemoji.load_yaml(Configuration::CODE_MAP_FILE).freeze
private_constant :CODES
end
| ruby | MIT | eecb84f7f2318b5239c5cd72c5323ec7056275f1 | 2026-01-04T17:44:35.040581Z | false |
jollygoodcode/twemoji | https://github.com/jollygoodcode/twemoji/blob/eecb84f7f2318b5239c5cd72c5323ec7056275f1/lib/twemoji/png.rb | lib/twemoji/png.rb | # frozen_string_literal: true
module Twemoji
def self.png
PNG
end
PNG = Twemoji.load_yaml(Configuration::PNG_MAP_FILE).freeze
private_constant :PNG
end
| ruby | MIT | eecb84f7f2318b5239c5cd72c5323ec7056275f1 | 2026-01-04T17:44:35.040581Z | false |
jollygoodcode/twemoji | https://github.com/jollygoodcode/twemoji/blob/eecb84f7f2318b5239c5cd72c5323ec7056275f1/lib/twemoji/utils/unicode.rb | lib/twemoji/utils/unicode.rb | # frozen_string_literal: true
module Twemoji
module Utils
module Unicode
# Convert raw unicode to string key version.
#
# e.g. 🇲🇾 converts to "1f1f2-1f1fe"
#
# @param unicode [String] Unicode codepoint.
# @param connector [String] (optional) connector to join codepoints
#
# @return [String] codepoints of unicode join by connector argument, defaults to "-".
def self.unpack(unicode, connector: "-")
unicode.split("").map { |r| "%x" % r.ord }.join(connector)
end
end
end
end
| ruby | MIT | eecb84f7f2318b5239c5cd72c5323ec7056275f1 | 2026-01-04T17:44:35.040581Z | false |
RiotGamesCookbooks/rbenv-cookbook | https://github.com/RiotGamesCookbooks/rbenv-cookbook/blob/a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3/metadata.rb | metadata.rb | name "rbenv"
maintainer "Riot Games"
maintainer_email "jamie@vialstudios.com"
license "Apache 2.0"
description "Installs and configures rbenv"
version "1.7.1"
recipe "rbenv", "Installs and configures rbenv"
recipe "rbenv::ruby_build", "Installs and configures ruby_build"
recipe "rbenv::ohai_plugin", "Installs an rbenv Ohai plugin to populate automatic_attrs about rbenv and ruby_build"
recipe "rbenv::rbenv_vars", "Installs an rbenv plugin rbenv-vars that lets you set global and project-specific environment variables before spawning Ruby processes"
%w{ centos redhat fedora ubuntu debian amazon oracle}.each do |os|
supports os
end
%w{ git build-essential apt }.each do |cb|
depends cb
end
depends 'ohai', '>= 1.1'
| ruby | Apache-2.0 | a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3 | 2026-01-04T17:44:35.905244Z | false |
RiotGamesCookbooks/rbenv-cookbook | https://github.com/RiotGamesCookbooks/rbenv-cookbook/blob/a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3/test/fixtures/cookbooks/fake/metadata.rb | test/fixtures/cookbooks/fake/metadata.rb | name 'fake'
version '1.0.0'
depends 'rbenv'
| ruby | Apache-2.0 | a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3 | 2026-01-04T17:44:35.905244Z | false |
RiotGamesCookbooks/rbenv-cookbook | https://github.com/RiotGamesCookbooks/rbenv-cookbook/blob/a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3/test/fixtures/cookbooks/fake/recipes/gem_install.rb | test/fixtures/cookbooks/fake/recipes/gem_install.rb | include_recipe 'fake::ruby_install'
rbenv_gem 'bundler' do
ruby_version node['fake']['ruby_version']
version '1.3.5'
end
| ruby | Apache-2.0 | a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3 | 2026-01-04T17:44:35.905244Z | false |
RiotGamesCookbooks/rbenv-cookbook | https://github.com/RiotGamesCookbooks/rbenv-cookbook/blob/a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3/test/fixtures/cookbooks/fake/recipes/ruby_install.rb | test/fixtures/cookbooks/fake/recipes/ruby_install.rb |
include_recipe 'rbenv::default'
include_recipe 'rbenv::ruby_build'
rbenv_ruby node['fake']['ruby_version'] do
global true
end
| ruby | Apache-2.0 | a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3 | 2026-01-04T17:44:35.905244Z | false |
RiotGamesCookbooks/rbenv-cookbook | https://github.com/RiotGamesCookbooks/rbenv-cookbook/blob/a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3/test/fixtures/cookbooks/fake/attributes/default.rb | test/fixtures/cookbooks/fake/attributes/default.rb |
default['fake']['ruby_version'] = '1.9.3-p448'
| ruby | Apache-2.0 | a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3 | 2026-01-04T17:44:35.905244Z | false |
RiotGamesCookbooks/rbenv-cookbook | https://github.com/RiotGamesCookbooks/rbenv-cookbook/blob/a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3/recipes/default.rb | recipes/default.rb | #
# Cookbook Name:: rbenv
# Recipe:: default
#
# Author:: Jamie Winsor (<jamie@vialstudios.com>)
#
# Copyright 2011-2012, Riot Games
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
node.set[:rbenv][:root] = rbenv_root_path
node.set[:ruby_build][:prefix] = "#{node[:rbenv][:root]}/plugins/ruby_build"
node.set[:ruby_build][:bin_path] = "#{node[:ruby_build][:prefix]}/bin"
case node[:platform]
when "ubuntu", "debian"
include_recipe "apt"
end
include_recipe "build-essential"
include_recipe "git"
package "curl"
case node[:platform]
when "redhat", "centos", "amazon", "oracle"
# TODO: add as per "rvm requirements"
package "openssl-devel"
package "zlib-devel"
package "readline-devel"
package "libxml2-devel"
package "libxslt-devel"
when "ubuntu", "debian"
package "libc6-dev"
package "automake"
package "libtool"
# https://github.com/sstephenson/ruby-build/issues/119
# "It seems your ruby installation is missing psych (for YAML
# output). To eliminate this warning, please install libyaml and
# reinstall your ruby."
package 'libyaml-dev'
# needed to unpack rubygems
package 'zlib1g'
package 'zlib1g-dev'
# openssl support for ruby
package "openssl"
package 'libssl-dev'
# readline for irb and rails console
package "libreadline-dev"
# for ruby stdlib rexml and nokogiri
# http://nokogiri.org/tutorials/installing_nokogiri.html
package "libxml2-dev"
package "libxslt1-dev"
# better irb support
package "ncurses-dev"
# for searching packages
package "pkg-config"
end
group node[:rbenv][:group] do
members node[:rbenv][:group_users] if node[:rbenv][:group_users]
end
user node[:rbenv][:user] do
shell "/bin/bash"
group node[:rbenv][:group]
supports :manage_home => node[:rbenv][:manage_home]
home node[:rbenv][:user_home]
end
directory node[:rbenv][:root] do
owner node[:rbenv][:user]
group node[:rbenv][:group]
mode "2775"
recursive true
end
with_home_for_user(node[:rbenv][:user]) do
git node[:rbenv][:root] do
repository node[:rbenv][:git_repository]
reference node[:rbenv][:git_revision]
user node[:rbenv][:user]
group node[:rbenv][:group]
action :sync
notifies :create, "template[/etc/profile.d/rbenv.sh]", :immediately
end
end
template "/etc/profile.d/rbenv.sh" do
source "rbenv.sh.erb"
mode "0644"
variables(
:rbenv_root => node[:rbenv][:root],
:ruby_build_bin_path => node[:ruby_build][:bin_path]
)
notifies :create, "ruby_block[initialize_rbenv]", :immediately
end
ruby_block "initialize_rbenv" do
block do
ENV['RBENV_ROOT'] = node[:rbenv][:root]
ENV['PATH'] = "#{node[:rbenv][:root]}/bin:#{node[:rbenv][:root]}/shims:#{node[:ruby_build][:bin_path]}:#{ENV['PATH']}"
end
action :nothing
end
# rbenv init creates these directories as root because it is called
# from /etc/profile.d/rbenv.sh But we want them to be owned by rbenv
# check https://github.com/sstephenson/rbenv/blob/master/libexec/rbenv-init#L71
%w{shims versions plugins}.each do |dir_name|
directory "#{node[:rbenv][:root]}/#{dir_name}" do
owner node[:rbenv][:user]
group node[:rbenv][:group]
mode "2775"
action [:create]
end
end
| ruby | Apache-2.0 | a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3 | 2026-01-04T17:44:35.905244Z | false |
RiotGamesCookbooks/rbenv-cookbook | https://github.com/RiotGamesCookbooks/rbenv-cookbook/blob/a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3/recipes/ohai_plugin.rb | recipes/ohai_plugin.rb | #
# Cookbook Name:: rbenv
# Recipe:: ohai_plugin
#
# Author:: Jamie Winsor (<jamie@vialstudios.com>)
#
# Copyright 2011-2012, Riot Games
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
include_recipe "ohai"
bin_path = ::File.join(rbenv_bin_path, "rbenv")
template "#{node[:ohai][:plugin_path]}/rbenv.rb" do
source 'plugins/rbenv.rb.erb'
owner 'root'
group 'root'
mode 0755
variables(
:rbenv_bin => bin_path
)
notifies :reload, "ohai[custom_plugins]", :immediately
end
| ruby | Apache-2.0 | a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3 | 2026-01-04T17:44:35.905244Z | false |
RiotGamesCookbooks/rbenv-cookbook | https://github.com/RiotGamesCookbooks/rbenv-cookbook/blob/a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3/recipes/ruby_build.rb | recipes/ruby_build.rb | #
# Cookbook Name:: rbenv
# Recipe:: ruby_build
#
# Author:: Jamie Winsor (<jamie@vialstudios.com>)
#
# Copyright 2011-2012, Riot Games
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
include_recipe "git"
with_home_for_user(node[:rbenv][:user]) do
git node[:ruby_build][:prefix] do
repository node[:ruby_build][:git_repository]
reference node[:ruby_build][:git_revision]
action :sync
user node[:rbenv][:user]
group node[:rbenv][:group]
end
end
| ruby | Apache-2.0 | a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3 | 2026-01-04T17:44:35.905244Z | false |
RiotGamesCookbooks/rbenv-cookbook | https://github.com/RiotGamesCookbooks/rbenv-cookbook/blob/a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3/recipes/rbenv_vars.rb | recipes/rbenv_vars.rb | #
# Cookbook Name:: rbenv
# Recipe:: rbenv_vars
#
# Author:: Deepak Kannan (<kannan.deepak@gmail.com>)
#
# Copyright 2011-2012, Riot Games
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
include_recipe "git"
plugin_path = "#{node[:rbenv][:root]}/plugins/rbenv-vars"
with_home_for_user(node[:rbenv][:user]) do
git plugin_path do
repository node[:rbenv_vars][:git_repository]
reference node[:rbenv_vars][:git_revision]
action :sync
user node[:rbenv][:user]
group node[:rbenv][:group]
end
end
| ruby | Apache-2.0 | a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3 | 2026-01-04T17:44:35.905244Z | false |
RiotGamesCookbooks/rbenv-cookbook | https://github.com/RiotGamesCookbooks/rbenv-cookbook/blob/a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3/providers/ruby.rb | providers/ruby.rb | #
# Cookbook Name:: rbenv
# Provider:: ruby
#
# Author:: Jamie Winsor (<jamie@vialstudios.com>)
#
# Copyright 2011-2012, Riot Games
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
include Chef::Mixin::Rbenv
action :install do
resource_descriptor = "rbenv_ruby[#{new_resource.name}] (version #{new_resource.ruby_version})"
if !new_resource.force && ruby_version_installed?(new_resource.ruby_version)
Chef::Log.debug "#{resource_descriptor} is already installed so skipping"
else
Chef::Log.info "#{resource_descriptor} is building, this may take a while..."
start_time = Time.now
out = new_resource.patch ?
rbenv_command("install --patch #{new_resource.ruby_version}", patch: new_resource.patch) :
rbenv_command("install #{new_resource.ruby_version}")
unless out.exitstatus == 0
raise Chef::Exceptions::ShellCommandFailed, "\n" + out.format_for_exception
end
Chef::Log.debug("#{resource_descriptor} build time was #{(Time.now - start_time)/60.0} minutes.")
chmod_options = {
user: node[:rbenv][:user],
group: node[:rbenv][:group],
cwd: rbenv_root_path
}
unless Chef::Platform.windows?
shell_out("chmod -R 0775 versions/#{new_resource.ruby_version}", chmod_options)
shell_out("find versions/#{new_resource.ruby_version} -type d -exec chmod +s {} \\;", chmod_options)
end
new_resource.updated_by_last_action(true)
end
if new_resource.global && !rbenv_global_version?(new_resource.name)
Chef::Log.info "Setting #{resource_descriptor} as the rbenv global version"
out = rbenv_command("global #{new_resource.ruby_version}")
unless out.exitstatus == 0
raise Chef::Exceptions::ShellCommandFailed, "\n" + out.format_for_exception
end
new_resource.updated_by_last_action(true)
end
end
| ruby | Apache-2.0 | a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3 | 2026-01-04T17:44:35.905244Z | false |
RiotGamesCookbooks/rbenv-cookbook | https://github.com/RiotGamesCookbooks/rbenv-cookbook/blob/a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3/providers/execute.rb | providers/execute.rb | #
# Cookbook Name:: rbenv
# Provider:: execute
#
# Author:: Jamie Winsor (<jamie@vialstudios.com>)
#
include Chef::Mixin::Rbenv
def load_current_resource
@path = [ rbenv_shims_path, rbenv_bin_path ] + new_resource.path + system_path
@environment = new_resource.environment
@environment["PATH"] = @path.join(":")
@environment["RBENV_ROOT"] = rbenv_root_path
@environment["RBENV_VERSION"] = new_resource.ruby_version if new_resource.ruby_version
new_resource.environment(@environment)
end
action :run do
execute "eval \"$(rbenv init -)\"" do
environment new_resource.environment
end
execute new_resource.name do
command new_resource.command
creates new_resource.creates
cwd new_resource.cwd
environment new_resource.environment
group new_resource.group
returns new_resource.returns
timeout new_resource.timeout
user new_resource.user
umask new_resource.umask
end
new_resource.updated_by_last_action(true)
end
private
def system_path
shell_out!("echo $PATH").stdout.chomp.split(':')
end
| ruby | Apache-2.0 | a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3 | 2026-01-04T17:44:35.905244Z | false |
RiotGamesCookbooks/rbenv-cookbook | https://github.com/RiotGamesCookbooks/rbenv-cookbook/blob/a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3/attributes/default.rb | attributes/default.rb | #
# Cookbook Name:: rbenv
# Attributes:: default
#
# Author:: Jamie Winsor (<jamie@vialstudios.com>)
#
# Copyright 2011-2012, Riot Games
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
default[:rbenv][:user] = "rbenv"
default[:rbenv][:group] = "rbenv"
default[:rbenv][:manage_home] = true
default[:rbenv][:group_users] = Array.new
default[:rbenv][:git_repository] = "https://github.com/sstephenson/rbenv.git"
default[:rbenv][:git_revision] = "master"
default[:rbenv][:install_prefix] = "/opt"
default[:rbenv][:root_path] = "#{node[:rbenv][:install_prefix]}/rbenv"
default[:rbenv][:user_home] = "/home/#{node[:rbenv][:user]}"
default[:ruby_build][:git_repository] = "https://github.com/sstephenson/ruby-build.git"
default[:ruby_build][:git_revision] = "master"
default[:rbenv_vars][:git_repository] = "https://github.com/sstephenson/rbenv-vars.git"
default[:rbenv_vars][:git_revision] = "master"
| ruby | Apache-2.0 | a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3 | 2026-01-04T17:44:35.905244Z | false |
RiotGamesCookbooks/rbenv-cookbook | https://github.com/RiotGamesCookbooks/rbenv-cookbook/blob/a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3/libraries/provider_rbenv_rubygems.rb | libraries/provider_rbenv_rubygems.rb | #
# Cookbook Name:: rbenv
# Library:: provider_rbenv_rubygems
#
# Author:: Jamie Winsor (<jamie@vialstudios.com>)
#
# Copyright 2011-2012, Riot Games
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require_relative 'chef_mixin_rbenv'
class Chef
class Provider
class Package
class RbenvRubygems < Chef::Provider::Package::Rubygems
include Chef::Mixin::Rbenv
class RbenvGemEnvironment < AlternateGemEnvironment
attr_reader :ruby_version
attr_reader :rbenv_root_path
alias_method :original_shell_out!, :shell_out!
include Chef::Mixin::Rbenv
def initialize(gem_binary_path, ruby_version, rbenv_root)
@ruby_version = ruby_version
@rbenv_root_path = rbenv_root
super(gem_binary_path)
end
def shell_out!(*args)
options = args.last.is_a?(Hash) ? args.pop : Hash.new
options.merge!(env: {
"RBENV_ROOT" => rbenv_root_path,
"RBENV_VERSION" => ruby_version,
"PATH" => ([ rbenv_shims_path, rbenv_bin_path ] + system_path).join(':')
})
original_shell_out!(*args, options)
end
private
def system_path
original_shell_out!("echo $PATH").stdout.chomp.split(':')
end
end
attr_reader :gem_binary_path
def initialize(new_resource, run_context = nil)
super
@gem_binary_path = gem_binary_path_for(new_resource.ruby_version)
@rbenv_root = node[:rbenv][:root_path]
@gem_env = RbenvGemEnvironment.new(gem_binary_path, new_resource.ruby_version, @rbenv_root)
end
def install_package(name, version)
install_via_gem_command(name, version)
rbenv_command("rehash")
true
end
def remove_package(name, version)
uninstall_via_gem_command(name, version)
true
end
def install_via_gem_command(name, version = nil)
src = @new_resource.source && " --source=#{@new_resource.source} --source=http://rubygems.org"
version_option = (version.nil? || version.empty?) ? "" : " -v \"#{version}\""
shell_out!(
"#{gem_binary_path} install #{name} -q --no-rdoc --no-ri #{version_option} #{src}#{opts}",
:user => node[:rbenv][:user],
:group => node[:rbenv][:group],
:env => {
'RBENV_VERSION' => @new_resource.ruby_version,
'RBENV_ROOT' => @rbenv_root
}
)
end
end
end
end
end
| ruby | Apache-2.0 | a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3 | 2026-01-04T17:44:35.905244Z | false |
RiotGamesCookbooks/rbenv-cookbook | https://github.com/RiotGamesCookbooks/rbenv-cookbook/blob/a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3/libraries/chef_mixin_rbenv.rb | libraries/chef_mixin_rbenv.rb | #
# Cookbook Name:: rbenv
# Library:: mixin_rbenv
#
# Author:: Jamie Winsor (<jamie@vialstudios.com>)
#
# Copyright 2011-2012, Riot Games
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'chef/mixin/shell_out'
class Chef
module Mixin
module Rbenv
include Chef::Mixin::ShellOut
def rbenv_command(cmd, options = {})
unless rbenv_installed?
Chef::Log.error("rbenv is not yet installed. Unable to run " +
"rbenv_command:`#{cmd}`. Are you trying to use " +
"`rbenv_command` at the top level of your recipe? " +
"This is known to cause this error")
raise "rbenv not installed. Can't run rbenv_command"
end
default_options = {
:user => node[:rbenv][:user],
:group => node[:rbenv][:group],
:cwd => rbenv_root_path,
:env => {
'RBENV_ROOT' => rbenv_root_path
},
:timeout => 3600
}
if patch = options.delete(:patch)
Chef::Log.info("Patch found at: #{patch}")
unless filterdiff_installed?
Chef::Log.error("Cannot find filterdiff. Please install patchutils to be able to use patches.")
raise "Cannot find filterdiff. Please install patchutils to be able to use patches."
end
shell_out("curl -fsSL #{patch} | filterdiff -x ChangeLog | #{rbenv_bin_path}/rbenv #{cmd}", Chef::Mixin::DeepMerge.deep_merge!(options, default_options))
else
shell_out("#{rbenv_bin_path}/rbenv #{cmd}", Chef::Mixin::DeepMerge.deep_merge!(options, default_options))
end
end
def rbenv_installed?
out = shell_out("ls #{rbenv_bin_path}/rbenv")
out.exitstatus == 0
end
def ruby_version_installed?(version)
out = rbenv_command("prefix", :env => { 'RBENV_VERSION' => version })
out.exitstatus == 0
end
def filterdiff_installed?
out = shell_out("which filterdiff")
out.exitstatus == 0
end
def rbenv_global_version?(version)
out = rbenv_command("global")
unless out.exitstatus == 0
raise Chef::Exceptions::ShellCommandFailed, "\n" + out.format_for_exception
end
global_version = out.stdout.chomp
global_version == version
end
def gem_binary_path_for(version)
"#{rbenv_prefix_for(version)}/bin/gem"
end
def rbenv_prefix_for(version)
out = rbenv_command("prefix", :env => { 'RBENV_VERSION' => version })
unless out.exitstatus == 0
raise Chef::Exceptions::ShellCommandFailed, "\n" + out.format_for_exception
end
prefix = out.stdout.chomp
end
def rbenv_bin_path
::File.join(rbenv_root_path, "bin")
end
def rbenv_shims_path
::File.join(rbenv_root_path, "shims")
end
def rbenv_root_path
node[:rbenv][:root_path]
end
# Ensures $HOME is temporarily set to the given user. The original
# $HOME is preserved and re-set after the block has been yielded
# to.
#
# This is a workaround for CHEF-3940. TL;DR Certain versions of
# `git` misbehave if configuration is inaccessible in $HOME.
#
# More info here:
#
# https://github.com/git/git/commit/4698c8feb1bb56497215e0c10003dd046df352fa
#
def with_home_for_user(username, &block)
time = Time.now.to_i
ruby_block "set HOME for #{username} at #{time}" do
block do
ENV['OLD_HOME'] = ENV['HOME']
ENV['HOME'] = begin
require 'etc'
Etc.getpwnam(username).dir
rescue ArgumentError # user not found
"/home/#{username}"
end
end
end
yield
ruby_block "unset HOME for #{username} #{time}" do
block do
ENV['HOME'] = ENV['OLD_HOME']
end
end
end
end
end
end
| ruby | Apache-2.0 | a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3 | 2026-01-04T17:44:35.905244Z | false |
RiotGamesCookbooks/rbenv-cookbook | https://github.com/RiotGamesCookbooks/rbenv-cookbook/blob/a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3/libraries/matchers.rb | libraries/matchers.rb | #
# Cookbook Name:: rbenv
# Library:: matchers
#
# Author:: Kai Forsthoevel (<kai.forsthoevel@injixo.com>)
#
# Copyright 2014, injixo
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
if defined?(ChefSpec)
def install_rbenv_ruby(ruby_version)
ChefSpec::Matchers::ResourceMatcher.new(:rbenv_ruby, :install, ruby_version)
end
def install_rbenv_gem(package_name)
ChefSpec::Matchers::ResourceMatcher.new(:rbenv_gem, :install, package_name)
end
def upgrade_rbenv_gem(package_name)
ChefSpec::Matchers::ResourceMatcher.new(:rbenv_gem, :upgrade, package_name)
end
def remove_rbenv_gem(package_name)
ChefSpec::Matchers::ResourceMatcher.new(:rbenv_gem, :remove, package_name)
end
def purge_rbenv_gem(package_name)
ChefSpec::Matchers::ResourceMatcher.new(:rbenv_gem, :purge, package_name)
end
def run_rbenv_execute(command)
ChefSpec::Matchers::ResourceMatcher.new(:rbenv_execute, :run, command)
end
end
| ruby | Apache-2.0 | a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3 | 2026-01-04T17:44:35.905244Z | false |
RiotGamesCookbooks/rbenv-cookbook | https://github.com/RiotGamesCookbooks/rbenv-cookbook/blob/a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3/libraries/chef_mixin_ruby_build.rb | libraries/chef_mixin_ruby_build.rb | #
# Cookbook Name:: rbenv
# Library:: mixin_ruby_build
#
# Author:: Jamie Winsor (<jamie@vialstudios.com>)
#
# Copyright 2011-2012, Riot Games
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'chef/mixin/shell_out'
class Chef
module Mixin
module RubyBuild
def ruby_build_binary_path
"#{node[:ruby_build][:bin_path]}/ruby-build"
end
def ruby_build_installed_version
out = shell_out("#{ruby_build_binary_path} --version", :env => nil)
out.stdout.chomp
end
end
end
end
| ruby | Apache-2.0 | a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3 | 2026-01-04T17:44:35.905244Z | false |
RiotGamesCookbooks/rbenv-cookbook | https://github.com/RiotGamesCookbooks/rbenv-cookbook/blob/a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3/libraries/recipe_ext.rb | libraries/recipe_ext.rb | #
# Cookbook Name:: rbenv
# Library:: recipe_ext
#
# Author:: Jamie Winsor (<jamie@vialstudios.com>)
#
# Copyright 2011-2012, Riot Games
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
class Chef
module Mixin
module Rbenv
# stub to satisfy RecipeExt (library load order not guaranteed)
end
end
module Rbenv
module RecipeExt
include Chef::Mixin::Rbenv
end
end
end
Chef::Recipe.send(:include, Chef::Rbenv::RecipeExt)
| ruby | Apache-2.0 | a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3 | 2026-01-04T17:44:35.905244Z | false |
RiotGamesCookbooks/rbenv-cookbook | https://github.com/RiotGamesCookbooks/rbenv-cookbook/blob/a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3/libraries/resource_ext.rb | libraries/resource_ext.rb | #
# Cookbook Name:: rbenv
# Library:: resource_ext
#
# Author:: Jamie Winsor (<jamie@vialstudios.com>)
#
# Copyright 2011-2012, Riot Games
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'chef/mixin/shell_out'
class Chef
module Mixin
module Rbenv
# stub to satisfy ResourceExt (library load order not guaranteed)
end
module RubyBuild
# stub to satisfy ResourceExt (library load order not guaranteed)
end
end
module Rbenv
module ResourceExt
include Chef::Mixin::Rbenv
include Chef::Mixin::RubyBuild
include Chef::Mixin::ShellOut
def desired_ruby_build_version?
if File.exists?(ruby_build_binary_path)
ruby_build_installed_version.match(/#{node[:ruby_build][:version]}$/).nil? ? false : true
else
false
end
end
end
end
end
Chef::Resource::Bash.send(:include, Chef::Rbenv::ResourceExt)
| ruby | Apache-2.0 | a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3 | 2026-01-04T17:44:35.905244Z | false |
RiotGamesCookbooks/rbenv-cookbook | https://github.com/RiotGamesCookbooks/rbenv-cookbook/blob/a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3/resources/ruby.rb | resources/ruby.rb | #
# Cookbook Name:: rbenv
# Resource:: ruby
#
# Author:: Jamie Winsor (<jamie@vialstudios.com>)
#
# Copyright 2011-2012, Riot Games
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
actions :install
attribute :name, :kind_of => String
attribute :ruby_version, :kind_of => String
attribute :force, :default => false
attribute :global, :default => false
attribute :patch, :default => nil
def initialize(*args)
super
@action = :install
@ruby_version ||= @name
end
| ruby | Apache-2.0 | a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3 | 2026-01-04T17:44:35.905244Z | false |
RiotGamesCookbooks/rbenv-cookbook | https://github.com/RiotGamesCookbooks/rbenv-cookbook/blob/a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3/resources/gem.rb | resources/gem.rb | #
# Cookbook Name:: rbenv
# Resource:: gem
#
# Author:: Jamie Winsor (<jamie@vialstudios.com>)
#
# Copyright 2011-2012, Riot Games
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
actions :install, :upgrade, :remove, :purge
attribute :package_name, :kind_of => String, :name_attribute => true
attribute :ruby_version, :kind_of => String
attribute :version, :kind_of => String
attribute :source, :kind_of => String
attribute :gem_binary, :kind_of => String
attribute :response_file, :kind_of => String
attribute :options, :kind_of => [String, Hash]
def initialize(*args)
super
@action = :install
@resource_name = :rbenv_gem
@provider = Chef::Provider::Package::RbenvRubygems
end
| ruby | Apache-2.0 | a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3 | 2026-01-04T17:44:35.905244Z | false |
RiotGamesCookbooks/rbenv-cookbook | https://github.com/RiotGamesCookbooks/rbenv-cookbook/blob/a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3/resources/execute.rb | resources/execute.rb | #
# Cookbook Name:: rbenv
# Resource:: execute
#
# Author:: Jamie Winsor (<jamie@vialstudios.com>)
#
actions :run
default_action :run
attribute :command, kind_of: [String, Array], name_attribute: true
attribute :creates, kind_of: String
attribute :cwd, kind_of: String
attribute :environment, kind_of: Hash, default: Hash.new
attribute :group, kind_of: [String, Integer]
attribute :path, kind_of: Array, default: Array.new
attribute :returns, kind_of: [Integer, Array]
attribute :timeout, kind_of: Integer
attribute :umask, kind_of: [String, Integer]
attribute :user, kind_of: [String, Integer]
attribute :ruby_version, kind_of: String
| ruby | Apache-2.0 | a7ae0eedbf678a8ac93456c325f9d69a8ac9d6f3 | 2026-01-04T17:44:35.905244Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/spec/ruco_spec.rb | spec/ruco_spec.rb | require "spec_helper"
describe Ruco do
it "has a VERSION" do
Ruco::OLD_VERSION.should =~ /^\d+\.\d+\.\d+(\.[a-z\d]+)?$/
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/spec/spec_helper.rb | spec/spec_helper.rb | $LOAD_PATH.unshift 'lib'
$ruco_colors = true
require 'ruco'
require 'timeout'
require 'tempfile'
silence_warnings do
Ruco::Editor::Colors::DEFAULT_THEME = 'spec/fixtures/test.tmTheme'
Ruco::OLD_VERSION = Ruco::VERSION
Ruco::VERSION = '0.0.0' # so tests dont fail if version gets longer
end
class Tempfile
def self.string_as_file(data)
result = nil
Tempfile.open('foo') do |f|
f.print data
f.close
result = yield(f.path)
end
result
end
end
class Time
def self.benchmark
t = Time.now.to_f
yield
Time.now.to_f - t
end
end
def log(text)
puts "LOG: #{text}"
end
RSpec.configure do |config|
config.expect_with(:rspec) { |c| c.syntax = [:expect, :should] }
config.mock_with :rspec do |mocks|
mocks.syntax = [:should, :receive]
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/spec/ruco/form_spec.rb | spec/ruco/form_spec.rb | require "spec_helper"
describe Ruco::Form do
let(:form){ Ruco::Form.new('Test', :columns => 30){|value| @result = value } }
it "positions cursor in text field" do
form.cursor.should == [0, 5]
end
describe :insert do
it "adds label size and input size" do
form.insert('abc')
form.cursor.should == [0, 8]
end
it "does not return result on normal insert" do
form.insert('abc')
@result.should == nil
end
it "returns result on enter" do
form.insert('abc')
form.insert("d\n")
@result.should == "abcd"
end
it "returns result on normal insert when auto_enter is given" do
form.instance_eval{ @options[:auto_enter] = true }
form.insert('a')
@result.should == 'a'
end
end
describe :move do
it "moves in text-field" do
form.insert('abc')
form.move(:relative, 0, -1)
form.cursor.should == [0,7]
end
it "cannot move out of left side" do
form.move(:relative, 0, -3)
form.cursor.should == [0,5]
end
it "cannot move out of right side" do
form.move(:relative, 0, 4)
form.cursor.should == [0,5]
form.insert('abc')
form.move(:relative, 0, 4)
form.cursor.should == [0,8]
end
end
describe :delete do
it "removes characters forward" do
form.insert('abc')
form.move(:relative, 0, -2)
form.delete(1)
form.view.should == 'Test ac'
end
it "removes characters backward" do
form.insert('abc')
form.move(:relative, 0, -1)
form.delete(-1)
form.view.should == 'Test ac'
end
it "moves the cursor backward" do
form.insert('abc')
form.move(:relative, 0, -1)
form.delete(-1)
form.cursor.should == [0,6]
end
end
describe :view do
it "can be viewed" do
form.view.should == "Test "
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/spec/ruco/editor_spec.rb | spec/ruco/editor_spec.rb | require "spec_helper"
describe Ruco::Editor do
def write(content)
File.open(@file,'wb'){|f| f.write(content) }
end
def read
File.binary_read(@file)
end
def color(c)
{
:string => ["#718C00", nil],
:keyword => ["#8959A8", nil],
:instance_variable => ["#C82829", nil],
}[c]
end
let(:language){ LanguageSniffer::Language.new(:name => 'ruby', :lexer => 'ruby') }
let(:editor){
editor = Ruco::Editor.new(@file, :lines => 3, :columns => 5, :language => language)
# only scroll when we reach end of lines/columns <-> able to test with smaller area
editor.send(:text_area).instance_eval{
@window.instance_eval{
@options[:line_scroll_threshold] = 0
@options[:line_scroll_offset] = 1
@options[:column_scroll_threshold] = 0
@options[:column_scroll_offset] = 1
}
}
editor
}
before do
`rm -rf ~/.ruco/sessions`
@file = 'spec/temp.txt'
write('')
end
describe "strange newline formats" do
it 'views \r normally' do
write("a\rb\rc\r")
editor.view.should == "a\nb\nc"
end
it 'views \r\n normally' do
write("a\r\nb\r\nc\r\n")
editor.view.should == "a\nb\nc"
end
it 'saves \r as \r' do
write("a\rb\rc\r")
editor.save
read.should == "a\rb\rc\r"
end
it 'saves \r\n as \r\n' do
write("a\r\nb\r\nc\r\n")
editor.save
read.should == "a\r\nb\r\nc\r\n"
end
it "converts mixed formats to first" do
write("a\rb\r\nc\n")
editor.save
read.should == "a\rb\rc\r"
end
it "converts newline-free to \n" do
write("a")
editor.insert("\n")
editor.save
read.should == "\na"
end
it "is not modified after saving strange newline format" do
write("a\r\nb\r\nc\r\n")
editor.save
editor.modified?.should == false
end
end
describe 'blank line before end of file on save' do
it "adds a newline" do
write("aaa")
editor = Ruco::Editor.new(@file, :lines => 3, :columns => 5, :blank_line_before_eof_on_save => true)
editor.save
read.should == "aaa\n"
end
it "does not add a newline without option" do
write("aaa")
editor = Ruco::Editor.new(@file, :lines => 3, :columns => 5)
editor.save
read.should == "aaa"
end
it "adds weird newline" do
write("aaa\r\nbbb")
editor = Ruco::Editor.new(@file, :lines => 3, :columns => 5, :blank_line_before_eof_on_save => true)
editor.save
read.should == "aaa\r\nbbb\r\n"
end
it "does not add a newline for empty lines" do
write("aaa\n ")
editor = Ruco::Editor.new(@file, :lines => 3, :columns => 5, :blank_line_before_eof_on_save => true)
editor.save
read.should == "aaa\n "
end
it "does not add a newline when one is there" do
write("aaa\n")
editor = Ruco::Editor.new(@file, :lines => 3, :columns => 5, :blank_line_before_eof_on_save => true)
editor.save
read.should == "aaa\n"
end
it "does not add a weird newline when one is there" do
write("aaa\r\n")
editor = Ruco::Editor.new(@file, :lines => 3, :columns => 5, :blank_line_before_eof_on_save => true)
editor.save
read.should == "aaa\r\n"
end
it "does not add a newline when many are there" do
write("aaa\n\n")
editor = Ruco::Editor.new(@file, :lines => 3, :columns => 5, :blank_line_before_eof_on_save => true)
editor.save
read.should == "aaa\n\n"
end
end
describe 'convert tabs' do
before do
write("\t\ta")
end
it "reads tab as spaces when option is set" do
editor = Ruco::Editor.new(@file, :lines => 3, :columns => 5, :convert_tabs => true)
editor.view.should == " a\n\n"
end
it "reads them normally when option is not set" do
editor = Ruco::Editor.new(@file, :lines => 3, :columns => 5)
editor.view.should == "\t\ta\n\n"
end
end
describe 'huge-files' do
it "does not try to open huge files" do
write('a'*(1024*1024 + 1))
lambda{
Ruco::Editor.new(@file, :lines => 3, :columns => 5)
}.should raise_error(RuntimeError)
end
it "opens large files and does not take forever" do
write('a'*(1024*1024))
Time.benchmark do
editor = Ruco::Editor.new(@file, :lines => 3, :columns => 5)
editor.view
end.should < 1
end
end
describe :move do
before do
write(" \n \n ")
end
it "starts at 0,0" do
editor.cursor.should == [0,0]
end
it "can move" do
editor.move(:relative, 1,2)
editor.cursor.should == [1,2]
editor.move(:relative, 1,1)
editor.cursor.should == [2,3]
end
it "can move in empty file" do
write("\n\n\n")
editor.move(:relative, 2,0)
editor.cursor.should == [2,0]
end
it "cannot move left/top off screen" do
editor.move(:relative, -1,-1)
editor.cursor.should == [0,0]
end
it "does not move lines when jumping right" do
editor.move(:relative, 1, 5)
editor.cursor.should == [1,4]
end
it "does not move lines when jumping left" do
editor.move(:to, 2, 2)
editor.move(:relative, -1, -5)
editor.cursor.should == [1,0]
end
it "moves to next line when moving right of characters" do
editor.move(:relative, 0, 5)
editor.cursor.should == [1,0]
end
it "moves to prev line when moving left of characters" do
editor.move(:relative, 1, 0)
editor.move(:relative, 0, -1)
editor.cursor.should == [0,4]
end
it "stays at origin when moving left" do
editor.move(:relative, 0, -1)
editor.cursor.should == [0,0]
end
it "stays at eof when moving right" do
editor.move(:to, 2, 4)
editor.move(:relative, 0, 1)
editor.cursor.should == [2,4]
end
it "stays in last line when moving past lines" do
write(" ")
editor.move(:relative, 6,3)
editor.cursor.should == [0,3]
end
describe 'column scrolling' do
it "can scroll columns" do
write("123456789\n123")
editor.move(:relative, 0,4)
editor.view.should == "12345\n123\n"
editor.cursor.column.should == 4
editor.move(:relative, 0,1)
editor.view.should == "34567\n3\n"
editor.cursor.column.should == 3
end
it "cannot scroll past the screen" do
write('123456789')
editor.move(:relative, 0,4)
6.times{ editor.move(:relative, 0,1) }
editor.view.should == "789\n\n"
editor.cursor.column.should == 3
end
it "can scroll columns backwards" do
write('0123456789')
editor.move(:relative, 0,5)
editor.view.should == "23456\n\n"
editor.move(:relative, 0,-4)
editor.view.should == "01234\n\n"
editor.cursor.column.should == 1
end
end
describe 'line scrolling' do
before do
write("1\n2\n3\n4\n5\n6\n7\n8\n9")
end
it "can scroll lines down" do
editor.move(:relative, 2,0)
editor.view.should == "1\n2\n3"
editor.move(:relative, 1,0)
editor.view.should == "3\n4\n5"
editor.cursor.line.should == 1
end
it "can scroll till end of file" do
editor.move(:relative, 15,0)
editor.view.should == "8\n9\n"
editor.cursor.line.should == 1
end
end
describe :to do
it "cannot move outside of text (bottom/right)" do
write("123\n456")
editor.move(:to, 10,10)
editor.cursor.should == [1,3]
end
it "cannot move outside of text (top/left)" do
write("123\n456")
editor.move(:relative, 1,1)
editor.move(:to, -10,-10)
editor.cursor.should == [0,0]
end
end
describe :to_eol do
before do
write("\n aa \n ")
end
it 'stays at start when line is empty' do
editor.move :to_eol
editor.cursor.should == [0,0]
end
it 'moves after last word if cursor was before it' do
editor.move(:relative, 1,1)
editor.move :to_eol
editor.cursor.should == [1,3]
end
it 'moves after last whitespace if cursor was after last word' do
editor.move(:relative, 1,3)
editor.move :to_eol
editor.cursor.should == [1,4]
end
it 'moves after last work if cursor was after last whitespace' do
editor.move(:relative, 1,4)
editor.move :to_eol
editor.cursor.should == [1,3]
end
end
describe :to_bol do
before do
write("\n aa \n ")
end
it 'stays at start when line is empty' do
editor.move :to_bol
editor.cursor.should == [0,0]
end
it 'moves before first work if at start of line' do
editor.move(:relative, 1,0)
editor.move :to_bol
editor.cursor.should == [1,2]
end
it 'moves to start of line if before first word' do
editor.move(:relative, 1,1)
editor.move :to_bol
editor.cursor.should == [1,0]
editor.move(:relative, 0,2)
editor.move :to_bol
editor.cursor.should == [1,0]
end
it 'moves before first word if inside line' do
editor.move(:relative, 1,5)
editor.move :to_bol
editor.cursor.should == [1,2]
end
end
describe 'jumping' do
it "can jump right" do
write("abc def")
editor.move(:jump, :right)
editor.cursor.should == [0,3]
end
it "does not jump over braces" do
write("abc(def")
editor.move(:jump, :right)
editor.cursor.should == [0,3]
end
it "can jump over whitespace and newlines" do
write("abc\n 123")
editor.move(:jump, :right)
editor.cursor.should == [0,3]
editor.move(:jump, :right)
editor.cursor.should == [1,1]
end
it "can jump left" do
write("abc def")
editor.move(:relative, 0,3)
editor.move(:jump, :left)
editor.cursor.should == [0,0]
end
it "can jump to start" do
write("abc\ndef")
editor.move(:relative, 0,2)
editor.move(:jump, :left)
editor.cursor.should == [0,0]
end
it "stays at start" do
write("abc\ndef")
editor.move(:jump, :left)
editor.cursor.should == [0,0]
end
it "can jump to end" do
write("abc\ndef")
editor.move(:relative, 1,1)
editor.move(:jump, :right)
editor.cursor.should == [1,3]
end
it "stays at end" do
write("abc\ndef")
editor.move(:to, 1,3)
editor.move(:jump, :right)
editor.cursor.should == [1,3]
end
end
end
describe :move_line do
before do
write("0\n1\n2\n")
end
it "moves the line" do
editor.move_line(1)
editor.view.should == "1\n0\n2"
end
it "keeps the cursor at the moved line" do
editor.move_line(1)
editor.cursor.should == [1,0]
end
it "keeps the cursor at current column" do
editor.move(:to, 0,1)
editor.move_line(1)
editor.cursor.should == [1,1]
end
it "uses indentation of moved-to-line" do
write(" 0\n 1\n 2\n")
editor.move_line(1)
editor.view.should == " 1\n 0\n 2"
end
it "cannot move past start of file" do
editor.move_line(-1)
editor.view.should == "0\n1\n2"
end
it "cannot move past end of file" do
write("0\n1\n")
editor.move_line(1)
editor.move_line(1)
editor.move_line(1)
editor.move_line(1)
editor.view.should == "1\n\n0"
end
end
describe :selecting do
before do
write('012345678')
end
it "remembers the selection" do
editor.selecting do
move(:to, 0, 4)
end
editor.selection.should == ([0,0]..[0,4])
end
it "expands the selection" do
editor.selecting do
move(:to, 0, 4)
move(:to, 0, 6)
end
editor.selection.should == ([0,0]..[0,6])
end
it "expand an old selection" do
editor.selecting do
move(:to, 0, 4)
end
editor.selecting do
move(:relative, 0, 2)
end
editor.selection.should == ([0,0]..[0,6])
end
it "can select backwards" do
editor.move(:to, 0, 4)
editor.selecting do
move(:relative, 0, -2)
end
editor.selecting do
move(:relative, 0, -2)
end
editor.selection.should == ([0,0]..[0,4])
end
it "can select multiple lines" do
write("012\n345\n678")
editor.move(:to, 0, 2)
editor.selecting do
move(:relative, 1, 0)
end
editor.selecting do
move(:relative, 1, 0)
end
editor.selection.should == ([0,2]..[2,2])
end
it "clears the selection once I move" do
editor.selecting do
move(:to, 0, 4)
end
editor.move(:relative, 0, 2)
editor.selection.should == nil
end
it "replaces the selection with insert" do
editor.selecting do
move(:to, 0, 4)
end
editor.insert('X')
editor.selection.should == nil
editor.cursor.should == [0,1]
editor.move(:to, 0,0)
editor.view.should == "X4567\n\n"
end
it "replaces the multi-line-selection with insert" do
write("123\n456\n789")
editor.move(:to, 0,1)
editor.selecting do
move(:to, 1,2)
end
editor.insert('X')
editor.selection.should == nil
editor.cursor.should == [0,2]
editor.move(:to, 0,0)
editor.view.should == "1X6\n789\n"
end
it "deletes selection delete" do
write("123\n456\n789")
editor.move(:to, 0,1)
editor.selecting do
move(:to, 1,2)
end
editor.delete(1)
editor.cursor.should == [0,1]
editor.move(:to, 0,0)
editor.view.should == "16\n789\n"
end
end
describe :text_in_selection do
before do
write("123\n456\n789")
end
it "returns '' if nothing is selected" do
editor.selecting do
move(:to, 1,1)
end
editor.text_in_selection.should == "123\n4"
end
it "returns selected text" do
editor.text_in_selection.should == ''
end
end
describe :style_map do
it "is empty by default" do
editor.style_map.flatten.should == [nil,nil,nil]
end
it "shows one-line selection" do
write('abcdefghi')
editor.selecting do
move(:to, 0, 4)
end
editor.style_map.flatten.should == [
[:reverse, nil, nil, nil, :normal],
nil,
nil
]
end
it "shows multi-line selection" do
write("abc\nabc\nabc")
editor.move(:to, 0,1)
editor.selecting do
move(:to, 1, 1)
end
editor.style_map.flatten.should == [
[nil, :reverse, nil, nil, nil, :normal],
[:reverse, :normal],
nil
]
end
it "shows the selection from offset" do
write('abcdefghi')
editor.move(:to, 0, 2)
editor.selecting do
move(:to, 0, 4)
end
editor.style_map.flatten.should == [
[nil, nil, :reverse, nil, :normal],
nil,
nil
]
end
it "shows the selection in nth line" do
write("\nabcdefghi")
editor.move(:to, 1, 2)
editor.selecting do
move(:to, 1, 4)
end
editor.style_map.flatten.should == [
nil,
[nil, nil, :reverse, nil, :normal],
nil
]
end
it "shows multi-line selection in scrolled space" do
write("\n\n\n\n\nacdefghijk\nacdefghijk\nacdefghijk\n\n")
ta = editor.send(:text_area)
ta.send(:position=, [5,8])
ta.send(:screen_position=, [5,7])
editor.selecting do
move(:relative, 2, 1)
end
editor.view.should == "ijk\nijk\nijk"
editor.cursor.should == [2,2]
editor.style_map.flatten.should == [
[nil, :reverse, nil, nil, nil, :normal], # start to end of screen
[:reverse, nil, nil, nil, nil, :normal], # 0 to end of screen
[:reverse, nil, :normal] # 0 to end of selection
]
end
it "shows keywords" do
write("class")
editor.style_map.flatten.should == [
[color(:keyword), nil, nil, nil, nil, :normal],
nil,
nil
]
end
it "shows keywords for moved window" do
write("\n\n\n\n\n if ")
editor.move(:to, 5, 6)
editor.cursor.should == [1,3]
editor.view.should == "\n if \n"
editor.style_map.flatten.should == [
nil,
[nil, nil, color(:keyword), nil, :normal],
nil
]
end
it "shows mid-keywords for moved window" do
write("\n\n\n\n\nclass ")
editor.move(:to, 5, 6)
editor.cursor.should == [1,3]
editor.view.should == "\nss \n"
editor.style_map.flatten.should == [
nil,
[color(:keyword), nil, :normal],
nil
]
end
it "shows multiple syntax elements" do
write("if @x")
editor.style_map.flatten.should == [
[color(:keyword), nil, :normal, color(:instance_variable), nil, :normal],
nil,
nil
]
end
it "does not show keywords inside strings" do
write("'Foo'")
editor.style_map.flatten.should == [
[color(:string), nil, nil, nil, nil, :normal],
nil,
nil
]
end
xit "shows multiline comments" do
write("=begin\na\nb\n=end")
editor.move(:to, 3,0)
editor.view.should == "b\n=end\n"
editor.style_map.flatten.should == [
[["#8E908C", nil], nil, :normal],
[["#8E908C", nil], nil, nil, nil, :normal],
nil
]
end
it "shows selection on top" do
write("class")
editor.selecting do
move(:relative, 0, 3)
end
editor.style_map.flatten.should == [
[:reverse, nil, nil, ["#8959A8", nil], nil, :normal],
nil,
nil
]
end
it "times out when styling takes too long" do
STDERR.should_receive(:puts)
Timeout.should_receive(:timeout).and_raise Timeout::Error
write(File.read('lib/ruco.rb'))
editor.style_map.flatten.should == [nil,nil,nil]
end
describe 'with theme' do
before do
write("class")
`rm -rf ~/.ruco/themes`
end
it "can download a theme" do
editor = Ruco::Editor.new(@file,
:lines => 3, :columns => 5, :language => language,
:color_theme => 'https://raw.github.com/ChrisKempson/TextMate-Tomorrow-Theme/master/Tomorrow-Night-Bright.tmTheme'
)
# TODO: randomly fails on ruby 3.0
# editor.style_map.flatten.should == [
# [["#C397D8", nil], nil, nil, nil, nil, :normal],
# nil,
# nil
# ]
end
it "does not fail with invalid theme url" do
STDERR.should_receive(:puts)
editor = Ruco::Editor.new(@file,
:lines => 3, :columns => 5, :language => language,
:color_theme => 'foooooo'
)
editor.style_map.flatten.should == [
[["#8959A8", nil], nil, nil, nil, nil, :normal],
nil,
nil
]
end
end
end
describe :view do
before do
write('')
end
it "displays an empty screen" do
editor.view.should == "\n\n"
end
it "displays short file content" do
write('xxx')
editor.view.should == "xxx\n\n"
end
it "displays long file content" do
write('1234567')
editor.view.should == "12345\n\n"
end
it "displays multiline-file content" do
write("xxx\nyyy\nzzz\niii")
editor.view.should == "xxx\nyyy\nzzz"
end
end
describe :insert do
before do
write('')
end
it "can insert new chars" do
write('123')
editor.move(:relative, 0,1)
editor.insert('ab')
editor.view.should == "1ab23\n\n"
editor.cursor.should == [0,3]
end
it "can insert new newlines" do
editor.insert("ab\nc")
editor.view.should == "ab\nc\n"
editor.cursor.should == [1,1]
end
it "jumps to correct column when inserting newline" do
write("abc\ndefg")
editor.move(:relative, 1,2)
editor.insert("1\n23")
editor.view.should == "abc\nde1\n23fg"
editor.cursor.should == [2,2]
end
it "jumps to correct column when inserting 1 newline" do
write("abc\ndefg")
editor.move(:relative, 1,2)
editor.insert("\n")
editor.view.should == "abc\nde\nfg"
editor.cursor.should == [2,0]
end
it "can add newlines to the end" do
write('')
editor.insert("\n")
editor.insert("\n")
editor.cursor.should == [2,0]
end
it "can add newlines to the moveable end" do
write('abc')
editor.move(:relative, 0,3)
editor.insert("\n")
editor.insert("\n")
editor.cursor.should == [2,0]
end
it "inserts tab as spaces" do
editor.insert("\t")
editor.view.should == " \n\n"
editor.cursor.should == [0,2]
end
it "keeps indentation" do
write("ab\n cd")
editor.move(:to, 1,2)
editor.insert("\n")
end
end
describe :indent do
it "indents selected lines" do
write("a\nb\nc\n")
editor.selecting{move(:to, 1,1)}
editor.indent
editor.view.should == " a\n b\nc"
end
it "moves the selection" do
write("a\nb\nc\n")
editor.selecting{move(:to, 1,1)}
editor.indent
editor.selection.should == ([0,2]..[1,3])
end
it "moves the cursor" do
write("a\nb\nc\n")
editor.selecting{move(:to, 1,1)}
editor.indent
editor.cursor.should == [1,3]
end
it "moves the cursor when selecting backward" do
write("a\nb\nc\n")
editor.move(:to, 1,1)
editor.selecting{move(:to, 0,1)}
editor.indent
editor.cursor.should == [0,3]
end
it "marks as modified" do
editor.selecting{move(:to, 0,1)}
editor.indent
editor.modified?.should == true
end
end
describe :unindent do
it "unindents single lines" do
write(" a\n\n")
editor.unindent
editor.view.should == " a\n\n"
end
it "unindents single lines by one" do
write(" a\n\n")
editor.unindent
editor.view.should == "a\n\n"
end
it "does not unindents single lines when not unindentable" do
write("a\n\n")
editor.unindent
editor.view.should == "a\n\n"
end
it "move the cursor when unindenting single line" do
write(" a\n\n")
editor.move(:to, 0,1)
editor.unindent
editor.cursor.should == [0,0]
end
it "unindents selected lines" do
write("a\n b\n c")
editor.selecting{ move(:to, 2,1) }
editor.unindent
editor.view.should == "a\nb\n c"
end
it "moves the selection" do
write(" abcd\n b\n c")
editor.move(:to, 0,3)
editor.selecting{ move(:to, 2,1) }
editor.unindent
editor.selection.should == ([0,1]..[2,0])
end
it "moves the selection when unindenting one space" do
write(" abcd\n b\n c")
editor.move(:to, 0,3)
editor.selecting{ move(:to, 2,1) }
editor.unindent
editor.selection.should == ([0,2]..[2,0])
end
it "does not move the selection when unindent is not possible" do
write("abcd\n b\n c")
editor.move(:to, 0,3)
editor.selecting{ move(:to, 2,1) }
editor.unindent
editor.selection.should == ([0,3]..[2,0])
end
it "moves the cursor when selecting forward" do
write("\n abcd\n")
editor.selecting{ move(:to, 1,3) }
editor.unindent
editor.cursor.should == [1,2]
end
it "moves the cursor when selecting backward" do
write(" x\n abcd\n")
editor.move(:to, 1,3)
editor.selecting{ move(:to, 0,1) }
editor.unindent
editor.cursor.should == [0,0]
end
end
describe 'history' do
it "does not overwrite the initial state" do
write("a")
editor.insert("b")
editor.view # trigger save point
stack = editor.history.stack
stack.length.should == 2
stack[0][:state][:content].should == "a"
stack[1][:state][:content].should == "ba"
editor.undo
editor.history.position.should == 0
editor.insert("c")
editor.view # trigger save point
stack.length.should == 2
stack[0][:state][:content].should == "a"
stack[1][:state][:content].should == "ca"
end
it "can undo an action" do
write("a")
editor.insert("b")
editor.view # trigger save point
future = Time.now + 10
Time.stub(:now).and_return future
editor.insert("c")
editor.view # trigger save point
editor.undo
editor.view.should == "ba\n\n"
editor.cursor.should == [0,1]
end
it "removes selection on undo" do
editor.insert('a')
editor.view # trigger save point
editor.selecting{move(:to, 1,1)}
editor.selection.should_not == nil
editor.view # trigger save point
editor.undo
editor.selection.should == nil
end
it "sets modified on undo" do
editor.insert('a')
editor.save
editor.modified?.should == false
editor.undo
editor.modified?.should == true
end
end
describe :save do
it 'stores the file' do
write('xxx')
editor.insert('a')
editor.save.should == true
File.binary_read(@file).should == 'axxx'
end
it 'creates the file' do
`rm #{@file}`
editor.insert('a')
editor.save.should == true
File.binary_read(@file).should == 'a'
end
it 'does not crash when it cannot save a file' do
begin
`chmod -w #{@file}`
editor.save.sub(" @ rb_sysopen", "").should == "Permission denied - #{@file}"
ensure
`chmod +w #{@file}`
end
end
describe 'remove trailing whitespace' do
it "can remove trailing whitespace" do
write("a \n \nb\n\n")
editor.move(:to, 0,2)
editor.instance_eval{@options[:remove_trailing_whitespace_on_save] = true}
editor.save
editor.view.should == "a\n\nb"
editor.cursor.should == [0,1]
end
it "does not affect trailing newlines" do
write("\n\n\n")
editor.move(:to, 2,0)
editor.instance_eval{@options[:remove_trailing_whitespace_on_save] = true}
editor.save
editor.view.should == "\n\n"
editor.cursor.should == [2,0]
end
it "does not remove trailing whitespace by default" do
write("a \n \nb\n\n")
editor.save
editor.view.should == "a \n \nb"
editor.cursor.should == [0,0]
end
end
end
describe :delete do
it 'removes a char' do
write('123')
editor.delete(1)
editor.view.should == "23\n\n"
editor.cursor.should == [0,0]
end
it 'removes a line' do
write("123\n45")
editor.move(:relative, 0,3)
editor.delete(1)
editor.view.should == "12345\n\n"
editor.cursor.should == [0,3]
end
it "cannot backspace over 0,0" do
write("aa")
editor.move(:relative, 0,1)
editor.delete(-3)
editor.view.should == "a\n\n"
editor.cursor.should == [0,0]
end
it 'backspaces a char' do
write('123')
editor.move(:relative, 0,3)
editor.delete(-1)
editor.view.should == "12\n\n"
editor.cursor.should == [0,2]
end
it 'backspaces a newline' do
write("1\n234")
editor.move(:relative, 1,0)
editor.delete(-1)
editor.view.should == "1234\n\n"
editor.cursor.should == [0,1]
end
end
describe :modified? do
it "is unchanged by default" do
editor.modified?.should == false
end
it "is changed after insert" do
editor.insert('x')
editor.modified?.should == true
end
it "is changed after delete" do
write("abc")
editor.delete(1)
editor.modified?.should == true
end
it "is not changed after move" do
editor.move(:relative, 1,1)
editor.modified?.should == false
end
it "is unchanged after save" do
editor.insert('x')
editor.save
editor.modified?.should == false
end
it "is changed after delete_line" do
write("\n\n\n")
editor.delete_line
editor.modified?.should == true
end
end
describe :find do
before do
write("\n ab\n ab")
end
it "moves to first occurrence" do
editor.find('ab')
editor.cursor.should == [1,1]
end
it "moves to next occurrence" do
editor.move(:relative, 1,1)
editor.find('ab')
editor.cursor.should == [2,1]
end
it "stays in place when nothing was found" do
editor.move(:relative, 2,1)
editor.find('ab')
editor.cursor.should == [2,1]
end
it "selects the occurrence" do
editor.find('ab')
editor.selection.should == ([1, 1]..[1, 3])
end
end
describe :delete_line do
before do
write("1\nlonger_than_columns\n56789")
end
it "removes the current line from first char" do
editor.move(:to, 1, 0)
editor.delete_line
editor.view.should == "1\n56789\n"
editor.cursor.should == [1, 0]
end
it "removes the current line from last char" do
editor.move(:to, 1, 3)
editor.delete_line
editor.view.should == "1\n56789\n"
editor.cursor.should == [1, 3]
end
it "can remove the first line" do
editor.delete_line
editor.view.should == "longe\n56789\n"
editor.cursor.should == [0, 0]
end
it "can remove the last line" do
write("aaa")
editor.delete_line
editor.view.should == "\n\n"
editor.cursor.should == [0, 0]
end
it "can remove the last line with lines remaining" do
write("aaa\nbbb")
editor.move(:to, 1,1)
editor.delete_line
editor.view.should == "aaa\n\n"
editor.cursor.should == [0, 1]
end
it "jumps to end of next lines end when put of space" do
write("1\n234\n5")
editor.move(:to, 1, 3)
editor.delete_line
editor.cursor.should == [1, 1]
end
it "can remove lines outside of initial screen" do
write("0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n")
editor.move(:to, 5, 0)
editor.move(:to, 6, 1)
editor.delete_line
editor.view.should == "5\n7\n8"
editor.cursor.should == [1, 1]
end
it "can remove the last line" do
write('xxx')
editor.delete_line
editor.insert('yyy')
editor.view.should == "yyy\n\n"
end
end
describe 'with line_numbers' do
let(:editor){ Ruco::Editor.new(@file, :lines => 5, :columns => 10, :line_numbers => true) }
before do
write("a\nb\nc\nd\ne\nf\ng\nh\n")
end
it "adds numbers to view" do
editor.view.should == " 1 a\n 2 b\n 3 c\n 4 d\n 5 e"
end
it "does not show numbers for empty lines" do
editor.move(:to, 10,0)
editor.view.should == " 6 f\n 7 g\n 8 h\n 9 \n "
end
it "adjusts the cursor" do
editor.cursor.should == [0,5]
end
it "adjusts the style map" do
editor.selecting{ move(:to, 0,1) }
editor.style_map.flatten.should == [
[nil, nil, nil, nil, nil, :reverse, nil, :normal],
nil, nil, nil, nil
]
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/spec/ruco/status_bar_spec.rb | spec/ruco/status_bar_spec.rb | require "spec_helper"
describe Ruco::StatusBar do
let(:file){ 'spec/temp.txt' }
let(:editor){ Ruco::Editor.new(file, :lines => 5, :columns => 35) }
let(:bar){ Ruco::StatusBar.new(editor, :columns => 35) }
it "shows name and version" do
bar.view.should include("Ruco #{Ruco::VERSION}")
end
it "shows the file" do
bar.view.should include(file)
end
it "can show to long files" do
editor = Ruco::Editor.new('123456789abcdefghijklmnop', :lines => 5, :columns => 20)
bar = Ruco::StatusBar.new(editor, :columns => 30)
bar.view.should == "Ruco #{Ruco::VERSION} -- 1234...nop 1:1"
bar.view.size.should == 30
end
it "indicates modified" do
bar.view.should_not include('*')
editor.insert('x')
bar.view.should include('*')
end
it "indicates writable" do
bar.view.should_not include('!')
end
it "indicates writable if file is missing" do
editor.stub(:file).and_return '/gradasadadsds'
bar.view.should_not include('!')
end
it "indicates not writable" do
# this test will always fail on Windows with cygwin because of how cygwin sets up permissions
unless RUBY_PLATFORM =~ /mingw/
editor.stub(:file).and_return '/etc/sudoers'
bar.view.should include('!')
end
end
it "shows line and column and right side" do
bar.view.should =~ /1:1$/
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/spec/ruco/history_spec.rb | spec/ruco/history_spec.rb | require "spec_helper"
describe Ruco::History do
let(:history){ Ruco::History.new(:state => {:x => 1}, :track => [:x], :entries => 3) }
it "knows its state" do
history.state.should == {:x => 1}
end
it "can add a state" do
history.add :x => 2
history.state.should == {:x => 2}
end
it "can undo a state" do
history.add :x => 2
history.undo
history.state.should == {:x => 1}
end
it "can undo-redo-undo a state" do
history.add :x => 2
history.undo
history.redo
history.state.should == {:x => 2}
end
it "cannot redo a modified stack" do
history.add :x => 2
history.undo
history.add :x => 3
history.redo
history.state.should == {:x => 3}
history.redo
history.state.should == {:x => 3}
end
it "cannot undo into nirvana" do
history.add :x => 2
history.undo
history.undo
history.state.should == {:x => 1}
end
it "cannot redo into nirvana" do
history.add :x => 2
history.redo
history.state.should == {:x => 2}
end
it "cannot undo unimportant changes" do
history.add(:x => 1, :y => 1)
history.undo
history.state.should == {:x => 1}
end
it "tracks unimportant fields when an important one changes" do
history.add(:x => 2, :y => 1)
history.add(:x => 3)
history.undo
history.state.should == {:x => 2, :y => 1}
history.undo
history.state.should == {:x => 1}
end
it "does not track more than x states" do
history.add(:x => 2)
history.add(:x => 3)
history.add(:x => 4)
history.add(:x => 5)
history.undo
history.undo
history.undo
history.undo
history.state.should == {:x => 3}
end
describe 'with strings' do
let(:history){ Ruco::History.new(:state => {:x => 'a'}, :track => [:x], :timeout => 0.1) }
it "triggers a new state on insertion and deletion" do
%w{ab abc ab a a}.each{|state| history.add(:x => state)}
history.undo
history.state.should == {:x => "abc"}
history.undo
history.state.should == {:x => "a"}
end
end
describe 'with timeout' do
let(:history){ Ruco::History.new(:state => {:x => 1}, :track => [:x], :entries => 3, :timeout => 0.1) }
it "adds fast changes" do
history.add(:x => 2)
history.add(:x => 3)
history.add(:x => 4)
history.undo
history.state.should == {:x => 1}
end
it "does not modify undone states" do
history.undo
history.state.should == {:x => 1}
history.add(:x => 4)
history.undo
history.state.should == {:x => 1}
end
it "does not modify redone states" do
history.add(:x => 2)
history.undo
sleep 0.2
history.redo
history.state.should == {:x => 2}
history.add(:x => 3)
history.undo
history.state.should == {:x => 2}
end
it "does not add slow changes" do
history.add(:x => 2)
history.add(:x => 3)
sleep 0.2
history.add(:x => 4)
history.undo
history.state.should == {:x => 3}
end
end
describe 'with no entry limit' do
let(:history){ Ruco::History.new(:state => {:x => 1}, :track => [:x], :entries => 0, :timeout => 0) }
it "should track unlimited states" do
200.times do |i|
history.add(:x => i+5)
end
history.stack.length.should == 201
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/spec/ruco/option_accessor_spec.rb | spec/ruco/option_accessor_spec.rb | require "spec_helper"
describe Ruco::OptionAccessor do
let(:options){ Ruco::OptionAccessor.new }
it "can be accessed like a hash" do
options[:xx].should == nil
options[:xx] = 1
options[:xx].should == 1
end
it "can be written" do
options.foo = true
options[:foo].should == true
end
it "can access nested keys" do
options.foo_bar = 1
options.history_size = 1
options.nested(:history).should == {:size => 1}
end
it "has empty hash for nested key" do
options.nested(:history).should == {}
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/spec/ruco/tm_theme_spec.rb | spec/ruco/tm_theme_spec.rb | require "spec_helper"
describe Ruco::TMTheme do
let(:theme){ Ruco::TMTheme.new('spec/fixtures/test.tmTheme') }
it "parses foreground/background" do
theme.foreground.should == '#4D4D4C'
theme.background.should == '#FFFFFF'
end
it "parses rules" do
theme.styles["keyword.operator.class"].should == ['#666969', nil]
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/spec/ruco/file_store_spec.rb | spec/ruco/file_store_spec.rb | require "spec_helper"
describe Ruco::FileStore do
def mark_all_as_old
store.send(:entries).each{|e| File.utime(1,1,e) }
end
before do
@folder = 'spec/sessions'
`rm -rf #{@folder}`
end
after do
`rm -rf #{@folder}`
end
let(:store){ Ruco::FileStore.new(@folder, :keep => 3) }
it "can get unstored stuff" do
store.get('xxx').should == nil
end
it "can store stuff" do
store.set('xxx', 1)
store.get('xxx').should == 1
end
it "can store :keep keys" do
store.set('xxx', 1)
store.set('yyy', 1)
store.set('zzz', 1)
mark_all_as_old
store.set('aaa', 2)
store.get('aaa').should == 2
['xxx','yyy','zzz'].map{|f| store.get(f) }.should =~ [1,1,nil]
end
it "does not drop if used multiple times" do
store.set('xxx', 1)
store.set('yyy', 1)
store.set('zzz', 1)
store.set('zzz', 1)
mark_all_as_old
store.set('zzz', 1)
store.set('zzz', 1)
store.get('xxx').should == 1
end
it "can cache" do
store.cache('x'){ 1 }.should == 1
store.cache('x'){ 2 }.should == 1
end
it "can cache false" do
store.cache('x'){ false }.should == false
store.cache('x'){ 2 }.should == false
end
it "does not cache nil" do
store.cache('x'){ nil }.should == nil
store.cache('x'){ 2 }.should == 2
end
it "can delete" do
store.set('x', 1)
store.set('y', 2)
store.delete('x')
store.get('x').should == nil
store.get('y').should == 2
end
it "can delete uncached" do
store.set('x', 1)
store.delete('z')
store.get('x').should == 1
store.get('z').should == nil
end
it "can clear" do
store.set('x', 1)
store.clear
store.get('x').should == nil
end
it "can clear unstored" do
store.clear
store.get('x').should == nil
end
it "can store pure strings" do
store = Ruco::FileStore.new(@folder, :keep => 3, :string => true)
store.set('xxx','yyy')
File.read(store.file('xxx')).should == 'yyy'
store.get('xxx').should == 'yyy'
end
it "works without colors" do
store = Ruco::FileStore.new(@folder)
store.set('xxx',1)
store.get('xxx').should == 1
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/spec/ruco/application_spec.rb | spec/ruco/application_spec.rb | # encoding: UTF-8
require "spec_helper"
describe Ruco::Application do
before do
`rm -rf ~/.ruco/sessions`
`rm #{rucorc} 2>&1`
@file = 'spec/temp.txt'
write('')
end
after do
`rm #{rucorc} 2>&1`
`rm -f #{@file}`
end
def write(content)
File.open(@file,'wb'){|f| f.write(content) }
end
def read
File.binary_read(@file)
end
def editor_part(view)
view.naive_split("\n")[1..-2].join("\n")
end
def type(*keys)
keys.each{|k| app.key k }
end
def status(line=1)
"Ruco #{Ruco::VERSION} -- spec/temp.txt #{line}:1\n"
end
let(:rucorc){ 'spec/.ruco.rb' }
let(:app){ Ruco::Application.new(@file, :lines => 5, :columns => 50, :rc => rucorc) }
let(:command){ "^W Exit ^S Save ^F Find ^R Replace" }
it "renders status + editor + command" do
write("xxx\nyyy\nzzz")
app.view.should == "#{status}xxx\nyyy\nzzz\n#{command}"
end
it "can enter stuff" do
app.key('2')
app.key('2')
app.key(:enter)
app.key('2')
app.key(:enter)
app.view.should == "#{status(3).sub('.txt ','.txt*')}2\n\n\n#{command}"
end
it "does not enter key-codes" do
app.key(888)
app.view.should == "#{status}\n\n\n#{command}"
end
it "can execute a command" do
write("123\n456\n789\n")
app.key(:"Ctrl+g") # go to line
app.key('2') # 2
app.key(:enter)
app.view.should == "#{status(2)}123\n456\n789\n#{command}"
app.cursor.should == [2,0] # 0 offset + 1 for statusbar
end
it "can resize" do
write("01234567\n1\n2\n3\n4\n5678910111213\n6\n7\n8")
app.resize(8, 7)
app.view.should == "Ruco 0.\n0123456\n1\n2\n3\n4\n5678910\n^W Exit"
end
describe 'opening with line' do
before do
write("\n1\n2\n3\n4\n5\n")
@file = @file+":2"
end
it "opens file at given line" do
app.cursor.should == [2,0]
app.view.should_not include(@file)
end
it "can save when opening with line" do
type 'a', :"Ctrl+s"
@file = @file[0..-3]
read.should == "\na1\n2\n3\n4\n5\n"
end
it "opens file with : if file with : exist" do
write("\n1\n2\n3\n4\n5\n")
app.view.should include(@file)
end
it "opens file with : if file with and without : do not exist" do
@file[-2..-1] = 'xxx:5'
app.cursor.should == [1,0]
app.view.should include(@file)
end
end
describe 'closing' do
it "can quit" do
result = app.key(:"Ctrl+w")
result.should == :quit
end
it "asks before closing changed file -- escape == no" do
app.key('a')
app.key(:"Ctrl+w")
app.view.split("\n").last.should include("Lose changes")
app.key(:escape).should_not == :quit
app.key("\n").should_not == :quit
end
it "asks before closing changed file -- enter == yes" do
app.key('a')
app.key(:"Ctrl+w")
app.view.split("\n").last.should include("Lose changes")
app.key(:enter).should == :quit
end
end
describe 'session' do
it "stores the session so I can reopen at the same position" do
write("0\n1\n2\n")
type :right, :down, :"Ctrl+q"
reopened = Ruco::Application.new(@file, :lines => 5, :columns => 10, :rc => rucorc)
reopened.cursor.should == [2,1]
end
it "does not store or restore content" do
write('')
type 'x', :"Ctrl+s", :enter, :enter, 'a', :"Ctrl+q"
reopened = Ruco::Application.new(@file, :lines => 5, :columns => 10, :rc => rucorc)
editor_part(reopened.view).should == "x\n\n"
end
end
it "can select all" do
write("1\n2\n3\n4\n5\n")
app.key(:down)
app.key(:"Ctrl+a")
app.key(:delete)
app.view.should include("\n\n\n")
end
describe 'go to line' do
it "goes to the line" do
write("\n\n\n")
app.key(:"Ctrl+g")
app.key('2')
app.key(:enter)
app.cursor.should == [2,0] # status bar + 2
end
it "goes to 1 when strange stuff entered" do
write("\n\n\n")
app.key(:"Ctrl+g")
app.key('0')
app.key(:enter)
app.cursor.should == [1,0] # status bar + 1
end
end
describe 'insert hash rocket' do
it "inserts an amazing hash rocket" do
write("")
app.key(:"Ctrl+l")
editor_part(app.view).should == " => \n\n"
end
end
describe 'Find and replace' do
it "stops when nothing is found" do
write 'abc'
type :"Ctrl+r", 'x', :enter
app.view.should_not include("Replace with:")
end
it "can find and replace multiple times" do
write 'xabac'
type :"Ctrl+r", 'a', :enter
app.view.should include("Replace with:")
type 'd', :enter
app.view.should include("Replace=Enter")
type :enter # replace first
app.view.should include("Replace=Enter")
type :enter # replace second -> finished
app.view.should_not include("Replace=Enter")
editor_part(app.view).should == "xdbdc\n\n"
end
it "can find and skip replace multiple times" do
write 'xabac'
type :"Ctrl+r", 'a', :enter
app.view.should include("Replace with:")
type 'd', :enter
app.view.should include("Replace=Enter")
type 's' # skip
app.view.should include("Replace=Enter")
type 's' # skip
app.view.should_not include("Replace=Enter")
editor_part(app.view).should == "xabac\n\n"
end
it "can replace all" do
write '_a_a_a_a'
type :"Ctrl+r", 'a', :enter
app.view.should include("Replace with:")
type 'd', :enter
app.view.should include("Replace=Enter")
type 's' # skip first
app.view.should include("Replace=Enter")
type 'a' # all
app.view.should_not include("Replace=Enter")
editor_part(app.view).should == "_a_d_d_d\n\n"
end
it "breaks if neither s nor enter is entered" do
write 'xabac'
type :"Ctrl+r", 'a', :enter
app.view.should include("Replace with:")
type "d", :enter
app.view.should include("Replace=Enter")
type 'x' # stupid user
app.view.should_not include("Replace=Enter")
editor_part(app.view).should == "xabac\n\n"
end
it "reuses find" do
write 'xabac'
type :"Ctrl+f", 'a', :enter
type :"Ctrl+r"
app.view.should include("Find: a")
type :enter
app.view.should include("Replace with:")
end
end
describe :bind do
it "can execute bound stuff" do
test = 0
app.bind :'Ctrl+q' do
test = 1
end
app.key(:'Ctrl+q')
test.should == 1
end
it "can execute an action via bind" do
test = 0
app.action :foo do
test = 1
end
app.bind :'Ctrl+q', :foo
app.key(:'Ctrl+q')
test.should == 1
end
end
describe 'indentation' do
it "does not extra-indent when pasting" do
Ruco.class_eval "Clipboard.copy('ab\n cd\n ef')"
app.key(:tab)
app.key(:tab)
app.key(:'Ctrl+v') # paste
editor_part(app.view).should == " cd\n ef\n"
end
it "indents when typing" do
app.key(:tab)
app.key(:tab)
app.key(:enter)
app.key('a')
editor_part(app.view).should == " \n a\n"
end
it "indents when at end of line and the next line has more whitespace" do
write("a\n b\n")
app.key(:right)
app.key(:enter)
app.key('c')
editor_part(app.view).should == "a\n c\n b"
end
it "indents when inside line and next line has more whitespace" do
write("ab\n b\n")
type :right, :enter, 'c'
editor_part(app.view).should == "a\n cb\n b"
end
it "indents when inside indented line" do
write(" ab\nc\n")
type :right, :right, :right, :enter, 'd'
editor_part(app.view).should == " a\n db\nc"
end
it "indents when tabbing on selection" do
write("ab")
app.key(:"Shift+right")
app.key(:tab)
editor_part(app.view).should == " ab\n\n"
end
it "unindents on Shift+tab" do
write(" ab\n cd\n")
app.key(:"Shift+tab")
editor_part(app.view).should == "ab\n cd\n"
end
end
describe '.ruco.rb' do
it "loads it and can use the bound keys" do
File.write(rucorc, "Ruco.configure{ bind(:'Ctrl+e'){ @editor.insert('TEST') } }")
app.view.should_not include('TEST')
app.key(:"Ctrl+e")
app.view.should include("TEST")
end
it "uses settings" do
File.write(rucorc, "Ruco.configure{ options.convert_tabs = true }")
app.options[:convert_tabs].should == true
end
it "passes settings to the window" do
File.write(rucorc, "Ruco.configure{ options.window_line_scroll_offset = 10 }")
app.send(:editor).send(:text_area).instance_eval{@window}.instance_eval{@options[:line_scroll_offset]}.should == 10
end
it "passes settings to history" do
File.write(rucorc, "Ruco.configure{ options.history_entries = 10 }")
app.send(:editor).send(:text_area).instance_eval{@history}.instance_eval{@options[:entries]}.should == 10
end
end
describe 'select mode' do
it "turns move commands into select commands" do
write('abc')
type :'Ctrl+b', :right, :right, 'a'
editor_part(app.view).should == "ac\n\n"
end
it "stops after first non-move command" do
write('abc')
type :'Ctrl+b', :right, 'd', :right, 'e'
editor_part(app.view).should == "dbec\n\n"
end
it "stops after hitting twice" do
write('abc')
type :'Ctrl+b', :'Ctrl+b', :right, 'd'
editor_part(app.view).should == "adbc\n\n"
end
end
describe 'find' do
def command_bar
app.view.split("\n").last
end
it "finds" do
write('text foo')
type :'Ctrl+f', 'foo', :enter
app.cursor.should == [1, 5]
end
it "marks the found word" do
write('text foo')
type :'Ctrl+f', 'foo', :enter, 'a'
editor_part(app.view).should == "text a\n\n"
end
it "shows a menu when nothing was found and there were previous matches" do
write('text bar bar foo')
type :'Ctrl+f', 'bar', :enter
type :'Ctrl+f', 'bar', :enter
type :'Ctrl+f', 'bar', :enter
command_bar.should include("No matches found")
end
it "returns to first match if user confirms after no more match is found" do
write('text foo foo')
type :'Ctrl+f', 'foo', :enter
app.cursor.should == [1, 5]
type :'Ctrl+f', 'foo', :enter
app.cursor.should == [1, 9]
type :'Ctrl+f', 'foo', :enter, :enter
app.cursor.should == [1, 5]
end
it "notifies the user when no matches are found in the entire file" do
write('text foo')
type :'Ctrl+f', 'bar', :enter
command_bar.should include("No matches found in entire file")
type :enter
command_bar.should_not include("No matches found in entire file")
end
it "dismisses the nothing found warning on a single key-press" do
write('text foo')
type :'Ctrl+f', 'bar', :enter
command_bar.should include("No matches found in entire file")
type 'a'
command_bar.should_not include("No matches found in entire file")
end
end
describe :save do
it "just saves" do
write('')
app.key('x')
app.key(:'Ctrl+s')
read.should == 'x'
end
it "warns when saving failed" do
begin
`chmod -w #{@file}`
app.key(:'Ctrl+s')
app.view.should include('Permission denied')
app.key(:enter) # retry ?
app.view.should include('Permission denied')
app.key(:escape)
app.view.should_not include('Permission denied')
ensure
`chmod +w #{@file}`
end
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/spec/ruco/text_area_spec.rb | spec/ruco/text_area_spec.rb | # encoding: utf-8
require "spec_helper"
describe Ruco::TextArea do
describe :move do
describe 'pages' do
it "can move down a page" do
text = Ruco::TextArea.new("1\n2\n3\n4\n5\n6\n7\n8\n9\n", :lines => 3, :columns => 3)
text.move(:page_down)
text.view.should == "3\n4\n5"
text.cursor.should == [1,0]
end
it "keeps cursor position when moving down" do
text = Ruco::TextArea.new("1\n2abc\n3\n4\n5ab\n6\n7\n8\n9\n", :lines => 3, :columns => 5)
text.move(:to, 1,4)
text.move(:page_down)
text.view.should == "4\n5ab\n6"
text.cursor.should == [1,3]
end
it "can move up a page" do
text = Ruco::TextArea.new("0\n1\n2\n3\n4\n5\n6\n7\n8\n", :lines => 3, :columns => 3)
text.move(:to, 4, 0)
text.view.should == "3\n4\n5"
text.cursor.should == [1,0]
text.move(:page_up)
text.view.should == "0\n1\n2"
text.cursor.should == [1,0]
end
it "keeps column position when moving up" do
text = Ruco::TextArea.new("0\n1\n2ab\n3\n4\n5abc\n6\n7\n8\n9\n10\n11\n", :lines => 3, :columns => 5)
text.move(:to, 5, 3)
text.view.should == "4\n5abc\n6"
text.cursor.should == [1,3]
text.move(:page_up)
text.view.should == "1\n2ab\n3"
text.cursor.should == [1,3]
end
it "moves pages symetric" do
text = Ruco::TextArea.new("0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n", :lines => 3, :columns => 3)
text.move(:to, 4, 1)
text.view.should == "3\n4\n5"
text.cursor.should == [1,1]
text.move(:page_down)
text.move(:page_down)
text.move(:page_up)
text.move(:page_up)
text.cursor.should == [1,1]
text.view.should == "3\n4\n5"
end
end
end
describe :insert do
let(:text){Ruco::TextArea.new("", :lines => 3, :columns => 10)}
describe "inserting surrounding characters" do
xit "does nothing special when pasting" do
text.insert("'bar'")
text.view.should == "'bar'\n\n"
text.cursor.should == [0,5]
end
xit "inserts a pair when just typing" do
text.insert("'")
text.view.should == "''\n\n"
text.cursor.should == [0,1]
end
xit "closes the surround if only char in surround" do
text.insert("'")
text.insert("'")
text.view.should == "''\n\n"
text.cursor.should == [0,2]
end
xit "overwrites next if its the same" do
text.insert("'bar'")
text.move(:relative, 0,-1)
text.insert("'")
text.view.should == "'bar'\n\n"
text.cursor.should == [0,5]
end
it "surrounds text when selecting" do
text.insert('bar')
text.move(:to, 0,0)
text.selecting{ move(:to, 0,2) }
text.insert("{")
text.view.should == "{ba}r\n\n"
text.cursor.should == [0,4]
end
it "does not surround text with closing char when selecting" do
text.insert('bar')
text.move(:to, 0,0)
text.selecting{ move(:to, 0,2) }
text.insert("}")
text.view.should == "}r\n\n"
text.cursor.should == [0,1]
end
it "replaces surrounding quotes" do
text.insert('"bar"')
text.move(:to, 0,0)
text.selecting{ move(:to, 0,5) }
text.insert("'")
text.view.should == "'bar'\n\n"
text.cursor.should == [0,5]
end
it "replace surrounding braces" do
text.insert('(bar)')
text.move(:to, 0,0)
text.selecting{ move(:to, 0,5) }
text.insert("'")
text.view.should == "'bar'\n\n"
text.cursor.should == [0,5]
end
it "does not replace when only one side has surrounding char" do
text.insert("\"bar\"")
text.move(:to, 0,0)
text.selecting{ move(:to, 0,3) }
text.insert("'")
text.view.should == "'\"ba'r\"\n\n"
text.cursor.should == [0,5]
end
it "expands selection when surrounding" do
text.insert('bar')
text.move(:to, 0,0)
text.selecting{ move(:to, 0,2) }
text.insert("{")
text.view.should == "{ba}r\n\n"
text.selection.should == ([0,0]..[0,4])
end
it "keeps selection when replacing surround" do
text.insert('"bar"')
text.move(:to, 0,0)
text.selecting{ move(:to, 0,5) }
text.insert("'")
text.view.should == "'bar'\n\n"
text.selection.should == ([0,0]..[0,5])
end
it "surrounds across lines" do
text.insert("ab\ncd\nef")
text.move(:to, 0,0)
text.selecting{ move(:to, 1,0) }
text.insert("'")
text.view.should == "'ab\n'cd\nef"
text.selection.should == ([0,0]..[1,1])
end
end
end
if ''.respond_to?(:encoding)
describe "encoding" do
def build(encoding)
Ruco::TextArea.new("asd".force_encoding(encoding), :lines => 3, :columns => 10)
end
it "upgrades ascii-8 to utf8" do
build('ASCII-8BIT').lines.first.encoding.to_s.should == 'UTF-8'
end
it "upgrades ascii-7 to utf8" do
build('US-ASCII').lines.first.encoding.to_s.should == 'UTF-8'
end
it "does not convert weird encodings to utf-8" do
build('eucJP').lines.first.encoding.to_s.should == 'EUC-JP'
end
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/spec/ruco/command_bar_spec.rb | spec/ruco/command_bar_spec.rb | require "spec_helper"
describe Ruco::CommandBar do
let(:default_view){ "^W Exit ^S Save ^F Find" }
let(:bar){ Ruco::CommandBar.new(:columns => 30) }
it "shows shortcuts by default" do
bar.view.should == default_view
end
it "shows less shortcuts when space is low" do
bar = Ruco::CommandBar.new(:columns => 29)
bar.view.should == default_view
bar = Ruco::CommandBar.new(:columns => 28)
bar.view.should == "^W Exit ^S Save"
end
describe :ask do
it "sets command bar into question mode" do
bar.ask('Find: '){}
bar.view.should == "Find: "
bar.cursor.column.should == 6
end
it "can enter answer" do
bar.ask('Find: '){}
bar.insert('abc')
bar.view.should == "Find: abc"
bar.cursor.column.should == 9
end
it "gets reset when submitting" do
bar.ask('Find: '){}
bar.insert("123\n")
bar.view.should == default_view
end
it "keeps entered answer when cached" do
bar.ask('Find: ', :cache => true){}
bar.insert('abc')
bar.insert("\n")
bar.ask('Find: ', :cache => true){}
bar.view.should == "Find: abc"
bar.cursor.column.should == 9
end
it "does not keep block when cached" do
x = 0
bar.ask('Find: ', :cache => true){ x = 1 }
bar.insert("\n")
bar.ask('Find: ', :cache => true){ x = 2 }
bar.insert("\n")
x.should == 2
end
it "reset the question when cached" do
bar.ask('Find: ', :cache => true){}
bar.insert('abc')
bar.reset
bar.view.should == default_view
bar.ask('Find: ', :cache => true){}
bar.view.should == "Find: " # term removed
end
it "does not reset all cached questions" do
bar.ask('Find: ', :cache => true){}
bar.insert("abc\n")
bar.ask('Foo: ', :cache => true){}
bar.reset # clears Foo not Find
bar.view.should == default_view
bar.ask('Find: ', :cache => true){}
bar.view.should == "Find: abc"
end
it "selects last value on cache-hit so I can type for new value" do
bar.ask('Find: ', :cache => true){}
bar.insert('abc')
bar.insert("\n")
bar.ask('Find: ', :cache => true){}
bar.cursor.column.should == 9
bar.text_in_selection.should == 'abc'
end
it "can re-find when reopening the find bar" do
@results = []
bar.ask('Find: ', :cache => true){|r| @results << r }
bar.insert('abc')
bar.insert("\n")
bar.ask('Find: ', :cache => true){|r| @results << r }
bar.insert("\n")
@results.should == ["abc","abc"]
end
it "gets reset when starting a new question" do
bar.ask('Find: '){}
bar.insert('123')
bar.ask('Find: '){}
bar.view.should == "Find: "
end
it "can execute" do
bar.ask('Find: ', :cache => true){|r| @result = r }
bar.insert('abc')
bar.insert("d\n")
@result.should == 'abcd'
end
end
describe :style_map do
let(:bar){ Ruco::CommandBar.new(:columns => 10) }
it "is reverse" do
bar.style_map.flatten.should == [[:reverse, nil, nil, nil, nil, nil, nil, nil, nil, nil, :normal]]
end
it "has normal style for selected input field" do
bar.ask('Q'){}
bar.insert('abc')
bar.selecting{ move(:to, 0,0) }
bar.view.should == 'Q abc'
bar.style_map.flatten.should == [[:reverse, nil, :normal, nil, nil, nil, :reverse, nil, nil, nil, nil, :normal]]
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/spec/ruco/array_processor_spec.rb | spec/ruco/array_processor_spec.rb | require "spec_helper"
describe Ruco::ArrayProcessor do
let(:p){ Ruco::ArrayProcessor.new }
before do
p.new_line('xxx')
end
it "is empty by default" do
p.lines.should == [[]]
end
it "parses simple syntax" do
p.open_tag('xxx',0)
p.close_tag('xxx',3)
p.lines.should == [[['xxx',0...3]]]
end
it "parses nested syntax" do
p.open_tag('xxx',0)
p.open_tag('yyy',2)
p.close_tag('yyy',3)
p.close_tag('xxx',3)
p.lines.should == [[["yyy", 2...3], ["xxx", 0...3]]]
end
it "parses multiline syntax" do
p.open_tag('xxx',0)
p.close_tag('xxx',3)
p.new_line('xxx')
p.open_tag('xxx',1)
p.close_tag('xxx',2)
p.lines.should == [
[["xxx", 0...3]],
[["xxx", 1...2]]
]
end
it "parses multiply nested syntax" do
p.open_tag('yyy',0)
p.open_tag('yyy',2)
p.close_tag('yyy',3)
p.close_tag('yyy',3)
p.lines.should == [[["yyy", 2...3], ["yyy", 0...3]]]
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/spec/ruco/syntax_parser_spec.rb | spec/ruco/syntax_parser_spec.rb | require "spec_helper"
describe Ruco::SyntaxParser do
def parse(text, languages=['ruby'])
Ruco::SyntaxParser.syntax_for_lines(text, languages)
end
describe :parse_lines do
it "shows positions for simple lines" do
parse(["class Foo","end"]).should == [[
["keyword.control.class.ruby", 0...5],
["entity.name.type.class.ruby", 6...9],
["meta.class.ruby", 0...9]],
[["keyword.control.ruby", 0...3]
]]
end
it "shows positions for complicated lines" do
parse(["class foo end blob else Foo"]).should == [[
["keyword.control.class.ruby", 0...5],
["entity.name.type.class.ruby", 6...9],
["meta.class.ruby", 0...9],
["keyword.control.ruby", 10...13],
["keyword.control.ruby", 19...23],
["variable.other.constant.ruby", 24...27]
]]
end
it "does not show keywords in strings" do
parse(["Bar 'Bar' foo"]).should == [[
["variable.other.constant.ruby", 0...3],
["punctuation.definition.string.begin.ruby", 4...5],
["punctuation.definition.string.end.ruby", 8...9],
["string.quoted.single.ruby", 4...9]
]]
end
it "does not show strings in comments" do
parse(["'Bar' # 'Bar'"]).should == [[
["punctuation.definition.string.begin.ruby", 0...1],
["punctuation.definition.string.end.ruby", 4...5],
["string.quoted.single.ruby", 0...5],
["punctuation.definition.comment.ruby", 6...7],
["comment.line.number-sign.ruby", 6...13]
]]
end
it "shows multiline comments" do
parse(["=begin","1 : 2","=end"]).should == [
[["punctuation.definition.comment.ruby", 0...6], ["comment.block.documentation.ruby", 0...7]],
[["comment.block.documentation.ruby", 0...6]],
[["punctuation.definition.comment.ruby", 0...4], ["comment.block.documentation.ruby", 0...4]]
]
end
it "continues multiline on last line before closing it" do
parse(["%Q{\n\na }"]).should == [
[["punctuation.definition.string.begin.ruby", 0...3], ["string.quoted.double.ruby.mod", 0...4]],
[["string.quoted.double.ruby.mod", 0...1]],
[["punctuation.definition.string.end.ruby", 3...4], ["string.quoted.double.ruby.mod", 0...4]]
]
end
it "can handle unfound syntaxes" do
parse('aaaa', ['fooo']).should == []
end
it "can handle RegexpErrors" do
parse(["(?# 2: NIL )(NIL)(?=[\\x80-\\xff(){ \\x00-\\x1f\\x7f%*\#{'\"'}\\\\\\[\\]+])|\\"])
end
end
describe :syntax_nodes do
it "detects languages not present in ultraviolet" do
Ruco::SyntaxParser.syntax_node(['html+erb']).should_not == nil
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/spec/ruco/window_spec.rb | spec/ruco/window_spec.rb | require "spec_helper"
describe Ruco::Window do
let(:window){ Ruco::Window.new(10,10) }
describe :crop do
let(:window){
Ruco::Window.new(2,4,
:line_scroll_threshold => 0, :line_scroll_offset => 1,
:column_scroll_threshold => 0, :column_scroll_offset => 1
)
}
it "does not modify given lines" do
original = ['1234','1234']
window.crop(original)
original.should == ['1234','1234']
end
it "removes un-displayable chars" do
result = window.crop(['12345','12345','12345'])
result.should == ['1234','1234']
end
it "does not add whitespace" do
result = window.crop(['1','',''])
result.should == ['1','']
end
it "creates lines if necessary" do
result = window.crop(['1234'])
result.should == ['1234','']
end
it "stays inside frame as long as position is in frame" do
window.position = Ruco::Position.new(1,3)
result = window.crop(['12345678','12345678'])
result.should == ['1234','1234']
end
it "can display empty lines" do
window.crop([]).should == ['','']
end
describe 'scrolled' do
it "goes out of frame if line is out of frame" do
window = Ruco::Window.new(6,1, :line_scroll_offset => 0, :line_scroll_threshold => 0)
window.position = Ruco::Position.new(6,0)
result = window.crop(['1','2','3','4','5','6','7','8','9'])
result.should == ['2','3','4','5','6','7']
end
it "goes out of frame if column is out of frame" do
window = Ruco::Window.new(1,6, :column_scroll_offset => 0, :column_scroll_threshold => 0)
window.position = Ruco::Position.new(0,6)
result = window.crop(['1234567890'])
result.should == ['234567']
end
end
end
describe :top do
let(:window){ Ruco::Window.new(10,10, :line_scroll_threshold => 1, :line_scroll_offset => 3) }
it "does not change when staying in frame" do
window.top.should == 0
window.position = Ruco::Position.new(8,0)
window.top.should == 0
end
it "changes by offset when going down out of frame" do
window.position = Ruco::Position.new(9,0)
window.top.should == 3
end
it "stays at bottom when going down out of frame" do
window.position = Ruco::Position.new(20,0)
window.top.should == 20 - 10 + 3 + 1
end
it "stays at top when going up out of frame" do
window.position = Ruco::Position.new(20,0)
window.position = Ruco::Position.new(7,0)
window.top.should == 7 - 3
end
it "changes to 0 when going up to 1" do
window.position = Ruco::Position.new(20,0)
window.position = Ruco::Position.new(1,0)
window.top.should == 0
end
it "does not change when staying in changed frame" do
window.position = Ruco::Position.new(9,0)
window.top.should == 3
window.position = Ruco::Position.new(11,0)
window.top.should == 3
end
end
describe :left do
let(:window){ Ruco::Window.new(10,10, :column_scroll_threshold => 1, :column_scroll_offset => 3) }
it "does not change when staying in frame" do
window.left.should == 0
window.position = Ruco::Position.new(0,8)
window.left.should == 0
end
it "changes by offset when going vertically out of frame" do
window.position = Ruco::Position.new(0,8)
window.position = Ruco::Position.new(0,9)
window.left.should == 3
end
it "stays right when going right out of frame" do
window.position = Ruco::Position.new(0,20)
window.left.should == 20 - 10 + 3 + 1
end
it "stays left when going left out of frame" do
window.position = Ruco::Position.new(0,20)
window.position = Ruco::Position.new(0,7)
window.left.should == 7 - 3
end
it "changes to 0 when going left out of frame to 1" do
window.position = Ruco::Position.new(0,20)
window.position = Ruco::Position.new(0,1)
window.left.should == 0
end
it "does not change when staying in changed frame" do
window.position = Ruco::Position.new(0,8)
window.position = Ruco::Position.new(0,9)
window.left.should == 3
window.position = Ruco::Position.new(0,11)
window.left.should == 3
end
end
describe :set_top do
it "sets" do
window.set_top 1, 20
window.top.should == 1
end
it "does not allow negative" do
window.set_top -1, 20
window.top.should == 0
end
it "does not go above maximum top" do
window.set_top 20, 20
window.top.should == 20 - 10 + 3 - 1
end
end
describe :left= do
it "sets" do
window.left = 1
window.left.should == 1
end
it "does not allow negative" do
window.left = -1
window.left.should == 0
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/spec/ruco/core_ext/string_spec.rb | spec/ruco/core_ext/string_spec.rb | require "spec_helper"
describe String do
describe :surrounded_in? do
[
['aba','a',true],
['abcab','ab',true],
['acc','a',false],
['cca','a',false],
['(cca)',['(',')'],true],
['(cca',['(',')'],false],
].each do |text, word, success|
it "is #{success} for #{word} in #{text}" do
text.surrounded_in?(*[*word]).should == success
end
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/spec/ruco/core_ext/array_spec.rb | spec/ruco/core_ext/array_spec.rb | require "spec_helper"
describe Array do
it "is bigger" do
[1].should > [0]
[1].should_not > [1]
end
it "is smaller" do
[1].should < [2]
[1].should_not < [1]
end
it "is smaller or equal" do
[1].should <= [1]
[1].should_not <= [0]
end
it "is bigger or equal" do
[1].should >= [1]
[1].should_not >= [2]
end
it "is between" do
[1].between?([1],[1]).should == true
[1].between?([1],[2]).should == true
[1].between?([0],[1]).should == true
[1].between?([0],[0]).should == false
[1].between?([2],[2]).should == false
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/spec/ruco/core_ext/range_spec.rb | spec/ruco/core_ext/range_spec.rb | require "spec_helper"
describe Range do
describe :move do
it "does not modify the original" do
a = 1..3
a.move(3)
a.should == (1..3)
end
it "can move 0" do
(1..3).move(0).should == (1..3)
end
it "can move right" do
(1..3).move(1).should == (2..4)
end
it "can move left" do
(1..3).move(-2).should == (-1..1)
end
it "can move exclusive ranges" do
(1...3).move(2).should == (3...5)
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco.rb | lib/ruco.rb | require 'dispel'
require 'language_sniffer'
require 'ruco/version'
require 'ruco/core_ext/object'
require 'ruco/core_ext/string'
require 'ruco/core_ext/array'
require 'ruco/core_ext/hash'
require 'ruco/core_ext/range'
require 'ruco/core_ext/file'
require 'ruco/position'
require 'ruco/history'
require 'ruco/option_accessor'
require 'ruco/file_store'
require 'ruco/window'
require 'ruco/syntax_parser'
require 'ruco/editor'
require 'ruco/editor/line_numbers'
require 'ruco/editor/history'
require 'ruco/status_bar'
require 'ruco/command_bar'
require 'ruco/application'
if $ruco_colors
begin
# there are some other gems out there like spox-textpow etc, so be picky
gem 'plist'
require 'plist'
gem 'textpow'
require 'textpow'
# we do not need there if any other color li failed
require 'ruco/array_processor'
require 'ruco/tm_theme'
require 'ruco/editor/colors'
rescue LoadError
warn "Could not load color libs -- #{$!}"
end
end
require 'ruco/form'
require 'ruco/text_area'
require 'ruco/editor_area'
require 'ruco/text_field'
module Ruco
autoload :Clipboard, 'clipboard' # can crash when loaded -> load if needed
TAB_SIZE = 2
class << self
attr_accessor :application
end
def self.configure(&block)
application.instance_exec(&block)
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/editor_area.rb | lib/ruco/editor_area.rb | module Ruco
# everything that does not belong to a text-area
# but is needed for Ruco::Editor
class EditorArea < TextArea
include Ruco::Editor::Colors if defined? Ruco::Editor::Colors # only colorize if all color libs are loaded
include Ruco::Editor::LineNumbers
include Ruco::Editor::History
def delete_line
lines.slice!(line, 1)
sanitize_position
end
def move_line(direction)
old = line
new = line + direction
return if new < 0
return if new >= lines.size
lines[old].leading_whitespace = lines[new].leading_whitespace
lines[old], lines[new] = lines[new], lines[old]
@line += direction
end
def indent
selected_lines.each do |line|
lines[line].insert(0, ' ' * Ruco::TAB_SIZE)
end
adjust_to_indentation Ruco::TAB_SIZE
end
def unindent
lines_to_unindent = (selection ? selected_lines : [line])
removed = lines_to_unindent.map do |line|
remove = [lines[line].leading_whitespace.size, Ruco::TAB_SIZE].min
lines[line].slice!(0, remove)
remove
end
adjust_to_indentation -removed.first, -removed.last
end
def state
{
:content => content,
:position => position,
:screen_position => screen_position
}
end
def state=(data)
@selection = nil
@lines = data[:content].naive_split("\n") if data[:content]
self.position = data[:position]
self.screen_position = data[:screen_position]
end
private
# TODO use this instead of instance variables
def screen_position
Position.new(@window.top, @window.left)
end
def screen_position=(pos)
@window.set_top(pos[0], @lines.size)
@window.left = pos[1]
end
def adjust_to_indentation(first, last=nil)
last ||= first
if selection
cursor_adjustment = (selection.first == position ? first : last)
selection.first.column = [selection.first.column + first, 0].max
selection.last.column = [selection.last.column + last, 0].max
self.column += cursor_adjustment
else
self.column += first
end
end
def selected_lines
selection.first.line.upto(selection.last.line)
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/array_processor.rb | lib/ruco/array_processor.rb | module Ruco
class ArrayProcessor
attr_accessor :lines
def initialize
@line_number = -1
@lines = []
@open_elements = []
@still_open_elements = []
end
def open_tag(name, position)
#puts "Open #{name} #{@line_number}:#{position}"
@open_elements << [name, position]
end
def close_tag(name, position)
#puts "Close #{name} #{@line_number}:#{position}"
open_element = @open_elements.pop || @still_open_elements.pop
@lines[@line_number] << [name, open_element.last...position]
end
def new_line(line)
#puts "Line #{line}"
# close elements only opened in last line
@open_elements.each do |name, position|
@lines[@line_number] << [name, position...@line.size]
end
# surround last line in still open elements from previouse lines
@still_open_elements.each do |name,_|
@lines[@line_number] << [name, 0...@line.size]
end
# mark open as 'still open'
# and let them start on column 0 -> if closed in this line its 0...position
@still_open_elements += @open_elements.map{|name,_| [name,0]}
@open_elements = []
# proceed with next line
@line = line
@line_number += 1
@lines[@line_number] = []
end
def start_parsing(name);end
def end_parsing(name);end
def inspect
@lines
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/status_bar.rb | lib/ruco/status_bar.rb | module Ruco
class StatusBar
def initialize(editor, options)
@editor = editor
@options = options
end
def view
columns = @options[:columns]
version = "Ruco #{Ruco::VERSION} -- "
position = " #{@editor.position.line + 1}:#{@editor.position.column + 1}"
indicators = "#{change_indicator}#{writable_indicator}"
essential = version + position + indicators
space_left = [columns - essential.size, 0].max
# fit file name into remaining space
file = @editor.file
file = file.ellipsize(:max => space_left)
space_left -= file.size
"#{version}#{file}#{indicators}#{' ' * space_left}#{position}"[0, columns]
end
def style_map
Dispel::StyleMap.single_line_reversed(@options[:columns])
end
def change_indicator
@editor.modified? ? '*' : ' '
end
def writable_indicator
@writable ||= begin
writable = (not File.exist?(@editor.file) or system("test -w #{@editor.file}"))
writable ? ' ' : '!'
end
end
private
# fill the line with left column and then overwrite the right section
def spread(left, right)
empty = [@options[:columns] - left.size, 0].max
line = left + (" " * empty)
line[(@options[:columns] - right.size - 1)..-1] = ' ' + right
line
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/version.rb | lib/ruco/version.rb | module Ruco
VERSION = Version = "0.5.0"
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/application.rb | lib/ruco/application.rb | module Ruco
class Application
attr_reader :editor, :status, :command, :options
def initialize(file, options)
@file, go_to_line = parse_file_and_line(file)
@options = OptionAccessor.new(options)
change_terminal_title
setup_actions
setup_keys
load_user_config
create_components
@editor.move(:to, go_to_line.to_i-1,0) if go_to_line
end
def display_info
[view, style_map, cursor]
end
def view
[status.view, editor.view, command.view].join("\n")
end
def style_map
status.style_map + editor.style_map + command.style_map
end
def cursor
Position.new(@focused.cursor.line + @status_lines, @focused.cursor.column)
end
# user typed a key
def key(key)
# deactivate select_mode if its not re-enabled in this action
@select_mode_was_on = @select_mode
@select_mode = false
if bound = @bindings[key]
return execute_action(bound)
end
case key
# move
when :down then move_with_select_mode :relative, 1,0
when :right then move_with_select_mode :relative, 0,1
when :up then move_with_select_mode :relative, -1,0
when :left then move_with_select_mode :relative, 0,-1
when :page_up then move_with_select_mode :page_up
when :page_down then move_with_select_mode :page_down
when :"Ctrl+right", :"Alt+f" then move_with_select_mode :jump, :right
when :"Ctrl+left", :"Alt+b" then move_with_select_mode :jump, :left
# select
when :"Shift+down" then @focused.selecting { move(:relative, 1, 0) }
when :"Shift+right" then @focused.selecting { move(:relative, 0, 1) }
when :"Shift+up" then @focused.selecting { move(:relative, -1, 0) }
when :"Shift+left" then @focused.selecting { move(:relative, 0, -1) }
when :"Ctrl+Shift+left", :"Alt+Shift+left" then @focused.selecting{ move(:jump, :left) }
when :"Ctrl+Shift+right", :"Alt+Shift+right" then @focused.selecting{ move(:jump, :right) }
when :"Shift+end" then @focused.selecting{ move(:to_eol) }
when :"Shift+home" then @focused.selecting{ move(:to_bol) }
# modify
when :tab then
if @editor.selection
@editor.indent
else
@focused.insert("\t")
end
when :"Shift+tab" then @editor.unindent
when :enter then @focused.insert("\n")
when :backspace then @focused.delete(-1)
when :delete then @focused.delete(1)
when :escape then # escape from focused
@focused.reset
@focused = editor
else
@focused.insert(key) if key.is_a?(String)
end
end
def bind(key, action=nil, &block)
raise "Ctrl+m cannot be bound" if key == :"Ctrl+m" # would shadow enter -> bad
raise "Cannot bind an action and a block" if action and block
@bindings[key] = action || block
end
def action(name, &block)
@actions[name] = block
end
def ask(question, options={}, &block)
@focused = command
command.ask(question, options) do |response|
@focused = editor
block.call(response)
end
end
def loop_ask(question, options={}, &block)
ask(question, options) do |result|
finished = (block.call(result) == :finished)
loop_ask(question, options, &block) unless finished
end
end
def configure(&block)
instance_exec(&block)
end
def resize(lines, columns)
@options[:lines] = lines
@options[:columns] = columns
create_components
@editor.resize(editor_lines, columns)
end
private
# http://stackoverflow.com/questions/3232655
# terminal tab in iterm2 holds 23 characters by default
def change_terminal_title
print "\e[22;0;t"
print "\e]0;#{@file.ellipsize(max: 23)}\007;"
at_exit { print "\e[23;0;t" }
end
def setup_actions
@actions = {}
action :paste do
@focused.insert(Clipboard.paste)
end
action :copy do
Clipboard.copy(@focused.text_in_selection)
end
action :cut do
Clipboard.copy(@focused.text_in_selection)
@focused.delete(0)
end
action :save do
result = editor.save
if result != true
ask("#{result.slice(0,100)} -- Enter=Retry Esc=Cancel "){ @actions[:save].call }
end
end
action :quit do
if editor.modified?
ask("Lose changes? Enter=Yes Esc=Cancel") do
editor.store_session
:quit
end
else
editor.store_session
:quit
end
end
action :go_to_line do
ask('Go to Line: ') do |result|
editor.move(:to_line, result.to_i - 1)
end
end
action :delete_line do
editor.delete_line
end
action :select_mode do
@select_mode = !@select_mode_was_on
end
action :select_all do
@focused.move(:to, 0, 0)
@focused.selecting do
move(:to, 9999, 9999)
end
end
action :find do
ask("Find: ", :cache => true) do |result|
next if editor.find(result)
if editor.content.include?(result)
ask("No matches found -- Enter=First match ESC=Stop") do
editor.move(:to, 0,0)
editor.find(result)
end
else
ask("No matches found in entire file", :auto_enter => true){}
end
end
end
action :find_and_replace do
ask("Find: ", :cache => true) do |term|
if editor.find(term)
ask("Replace with: ", :cache => true) do |replace|
loop_ask("Replace=Enter Skip=s All=a Cancel=Esc", :auto_enter => true) do |ok|
case ok
when '' # enter
editor.insert(replace)
when 'a'
stop = true
editor.insert(replace)
editor.insert(replace) while editor.find(term)
when 's' # do nothing
else
stop = true
end
:finished if stop or not editor.find(term)
end
end
end
end
end
action(:undo){ @editor.undo if @focused == @editor }
action(:redo){ @editor.redo if @focused == @editor }
action(:move_line_up){ @editor.move_line(-1) if @focused == @editor }
action(:move_line_down){ @editor.move_line(1) if @focused == @editor }
action(:move_to_eol){ move_with_select_mode :to_eol }
action(:move_to_bol){ move_with_select_mode :to_bol }
action(:insert_hash_rocket){ @editor.insert(' => ') }
end
def setup_keys
@bindings = {}
bind :"Ctrl+s", :save
bind :"Ctrl+w", :quit
bind :"Ctrl+q", :quit
bind :"Ctrl+g", :go_to_line
bind :"Ctrl+f", :find
bind :"Ctrl+r", :find_and_replace
bind :"Ctrl+b", :select_mode
bind :"Ctrl+a", :select_all
bind :"Ctrl+d", :delete_line
bind :"Ctrl+l", :insert_hash_rocket
bind :"Ctrl+x", :cut
bind :"Ctrl+c", :copy
bind :"Ctrl+v", :paste
bind :"Ctrl+z", :undo
bind :"Ctrl+y", :redo
bind :"Alt+Ctrl+down", :move_line_down
bind :"Alt+Ctrl+up", :move_line_up
bind :end, :move_to_eol
bind :"Ctrl+e", :move_to_eol # for OsX
bind :home, :move_to_bol
end
def load_user_config
Ruco.application = self
config = File.expand_path(@options[:rc] || "~/.ruco.rb")
load config if File.exist?(config)
end
def create_components
@status_lines = 1
editor_options = @options.slice(
:columns, :convert_tabs, :convert_newlines, :undo_stack_size, :color_theme
).merge(
:window => @options.nested(:window),
:history => @options.nested(:history),
:lines => editor_lines
).merge(@options.nested(:editor))
@editor ||= Ruco::Editor.new(@file, editor_options)
@status = Ruco::StatusBar.new(@editor, @options.nested(:status_bar).merge(:columns => options[:columns]))
@command = Ruco::CommandBar.new(@options.nested(:command_bar).merge(:columns => options[:columns]))
command.cursor_line = editor_lines
@focused = @editor
end
def editor_lines
command_lines = 1
@options[:lines] - @status_lines - command_lines
end
def parse_file_and_line(file)
if file.to_s.include?(':') and not File.exist?(file)
short_file, go_to_line = file.split(':',2)
if File.exist?(short_file)
file = short_file
else
go_to_line = nil
end
end
[file, go_to_line]
end
def move_with_select_mode(*args)
@select_mode = true if @select_mode_was_on
if @select_mode
@focused.selecting do
move(*args)
end
else
@focused.send(:move, *args)
end
end
def execute_action(action)
if action.is_a?(Symbol)
@actions[action].call
else
action.call
end
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/text_field.rb | lib/ruco/text_field.rb | module Ruco
class TextField < TextArea
def initialize(options)
super('', options.merge(:lines => 1))
end
def view
super.gsub("\n",'')
end
def value
content.gsub("\n",'')
end
end
end | ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/window.rb | lib/ruco/window.rb | module Ruco
class Window
OFFSET = 5
attr_accessor :lines, :columns, :left
attr_reader :cursor, :top
def initialize(lines, columns, options={})
@options = options
@options[:line_scroll_threshold] ||= 1
@options[:line_scroll_offset] ||= 1
@options[:column_scroll_threshold] ||= 1
@options[:column_scroll_offset] ||= 5
@lines = lines
@columns = columns
@top = 0
@left = 0
@cursor = Position.new(0,0)
end
def position=(x)
set_position(x)
end
def set_position(position, options={})
scroll_line_into_view position.line, (options[:max_lines] || 9999)
scroll_column_into_view position.column
@cursor = Position.new(position.line - @top, position.column - @left)
end
def crop(lines)
lines_to_display = lines[visible_lines] || []
lines_to_display[@lines-1] ||= nil
lines_to_display.map do |line|
line ||= ''
line[visible_columns] || ''
end
end
def scroll_line_into_view(line, total_lines)
result = adjustment(line, visible_lines, @options[:line_scroll_threshold], @options[:line_scroll_offset])
set_top result, total_lines if result
end
def scroll_column_into_view(column)
result = adjustment(column, visible_columns, @options[:column_scroll_threshold], @options[:column_scroll_offset])
self.left = result if result
end
def style_map(selection)
map = Dispel::StyleMap.new(lines)
if selection
add_selection_styles(map, selection)
else
map
end
end
def add_selection_styles(map, selection)
lines.times do |line|
visible = visible_area(line)
next unless selection.overlap?(visible)
first = [selection.first, visible.first].max
first = first[1] - left
last = [selection.last, visible.last].min
last = last[1] - left
map.add(:reverse, line, first...last)
end
map
end
def left=(x)
@left = [x,0].max
end
def set_top(line, total_lines)
max_top = total_lines - lines + 1 + @options[:line_scroll_offset]
@top = [[line, max_top].min, 0].max
end
def visible_lines
@top..(@top+@lines-1)
end
def visible_columns
@left..(@left+@columns-1)
end
private
def adjustment(current, allowed, threshold, offset)
if current < (allowed.first + threshold)
current - offset
elsif current > (allowed.last - threshold)
size = allowed.last - allowed.first + 1
current - size + 1 + offset
end
end
def visible_area(line)
line += @top
start_of_line = [line, @left]
last_visible_column = @left + @columns
end_of_line = [line, last_visible_column]
start_of_line..end_of_line
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/form.rb | lib/ruco/form.rb | module Ruco
class Form
delegate :move, :delete, :value, :selecting, :selection, :text_in_selection, :to => :text_field
def initialize(label, options, &submit)
@options = options
@label = label.strip + ' '
@submit = submit
reset
end
def view
@label + @text_field.view
end
def style_map
map = @text_field.style_map
map.left_pad!(@label.size)
map
end
def insert(text)
@text_field.insert(text.gsub("\n",'')) unless text == "\n"
@submit.call(@text_field.value) if text.include?("\n") or @options[:auto_enter]
end
def cursor
Position.new 0, @label.size + @text_field.cursor.column
end
def reset
@text_field = TextField.new(:columns => @options[:columns] - @label.size)
end
private
attr_reader :text_field
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/text_area.rb | lib/ruco/text_area.rb | module Ruco
class TextArea
SURROUNDING_CHARS = {
'<' => '>',
'(' => ')',
'[' => ']',
'{' => '}',
'"' => '"',
"'" => "'",
"`" => "`",
'/' => '/'
}
attr_reader :lines, :selection, :column, :line
def initialize(content, options)
if content.respond_to?(:encoding) and content.encoding.to_s.include?('ASCII')
content = content.force_encoding('UTF-8')
end
@lines = content.naive_split("\n")
@options = options.dup
@column = 0
@line = 0
@window = Window.new(@options.delete(:lines), @options.delete(:columns), @options[:window]||{})
adjust_window
end
def view
adjust_window
@window.crop(lines) * "\n"
end
def cursor
adjust_window
@window.cursor
end
def style_map
adjust_window
@window.style_map(@selection)
end
def move(where, *args)
case where
when :relative
move_relative(*args)
when :to
self.line, self.column = args
when :to_bol then move_to_bol(*args)
when :to_eol then move_to_eol(*args)
when :to_line then self.line = args.first
when :to_column then self.column = args.first
when :to_index then move(:to, *position_for_index(*args))
when :page_down
self.line += @window.lines
@window.set_top(@window.top + @window.lines, @lines.size)
when :page_up
self.line -= @window.lines
@window.set_top(@window.top - @window.lines, @lines.size)
when :jump
move_jump(args.first)
else
raise "Unknown move type #{where} with #{args.inspect}"
end
@selection = nil unless @selecting
end
def selecting(&block)
start = if @selection
(position == @selection.first ? @selection.last : @selection.first)
else
position
end
@selecting = true
instance_exec(&block)
@selecting = false
sorted = [start, position].sort
@selection = sorted[0]..sorted[1]
end
def text_in_selection
return '' unless @selection
start = index_for_position(@selection.first)
finish = index_for_position(@selection.last)
content.slice(start, finish-start)
end
def reset
@selection = nil
end
def insert(text)
text = text.force_encoding('UTF-8')
if @selection
if SURROUNDING_CHARS[text]
return surround_selection_with(text)
else
delete_content_in_selection
end
end
text.tabs_to_spaces!
if text == "\n" and @column >= current_line.leading_whitespace.size
current_whitespace = current_line.leading_whitespace
next_whitespace = lines[line+1].to_s.leading_whitespace
text = text + [current_whitespace, next_whitespace].max
end
insert_into_content text
move_according_to_insert text
end
def delete(count)
if @selection
delete_content_in_selection
return
end
if count > 0
if current_line[@column..-1].size >= count
current_line.slice!(@column, count)
else
with_lines_as_string do |content|
content.slice!(index_for_position, count)
end
end
else
backspace(count.abs)
end
end
def index_for_position(position=self.position)
lines[0...position.line].sum{|l| l.size + 1} + position.column
end
def content
(lines * "\n").freeze
end
def resize(lines, columns)
@window.lines = lines
@window.columns = columns
end
def position
Position.new(line, column)
end
protected
def position_for_index(index)
jump = content.slice(0, index).to_s.naive_split("\n")
[jump.size - 1, jump.last.size]
end
def with_lines_as_string
string = @lines * "\n"
yield string
@lines = string.naive_split("\n")
end
def after_last_word
current_line.index(/\s*$/)
end
def move_to_eol
after_last_whitespace = current_line.size
if @column == after_last_whitespace or @column < after_last_word
move :to_column, after_last_word
else
move :to_column, after_last_whitespace
end
end
def move_to_bol
before_first_word = current_line.index(/[^\s]/) || 0
column = if @column == 0 or @column > before_first_word
before_first_word
else
0
end
move :to_column, column
end
def move_relative(line_change, column_change)
if line_change == 0
# let user wrap around start/end of line
move :to_index, index_for_position + column_change
else
# normal movement
self.line += line_change
self.column += column_change
end
end
def move_jump(direction)
regex = /\b/m
text = content
next_index = if direction == :right
text.index(regex, index_for_position + 1) || text.size
else
text.rindex(regex,[index_for_position - 1, 0].max) || 0
end
move :to_index, next_index
end
def backspace(count)
if @column >= count
new_colum = @column - count
current_line.slice!(new_colum, count)
move :to_column, new_colum
else
start_index = index_for_position - count
if start_index < 0
count += start_index
start_index = 0
end
with_lines_as_string do |content|
content.slice!(start_index, count)
end
move :to, *position_for_index(start_index)
end
end
def line=(x)
@line = [[x, 0].max, [lines.size - 1, 0].max ].min
self.column = @column # e.g. now in an empty line
end
def column=(x)
@column = [[x, 0].max, current_line.size].min
end
def position=(pos)
self.line, self.column = pos
end
def insert_into_content(text)
if text.include?("\n")
with_lines_as_string do |content|
content.insert(index_for_position, text)
end
else
# faster but complicated for newlines
lines[line] ||= ''
lines[line].insert(@column, text)
end
end
def position_inside_content?
line < lines.size and @column < lines[line].to_s.size
end
def current_line
lines[line] || ''
end
def move_according_to_insert(text)
inserted_lines = text.naive_split("\n")
if inserted_lines.size > 1
self.line += inserted_lines.size - 1
self.column = inserted_lines.last.size
else
move(:relative, inserted_lines.size - 1, inserted_lines.last.size)
end
end
def delete_content_in_selection
with_lines_as_string do |content|
start = index_for_position(@selection.first)
finish = index_for_position(@selection.last)
content.slice!(start, finish-start)
move(:to, *@selection.first)
end
@selection = nil
end
def sanitize_position
self.line = line
self.column = column
end
def adjust_window
sanitize_position
@window.set_position(position, :max_lines => @lines.size)
end
def surround_selection_with(text)
open_char = text
close_char = SURROUNDING_CHARS[text]
old_selection = @selection.deep_copy
selected = text_in_selection
replace_surrounding_chars = SURROUNDING_CHARS.any?{|chars| selected.surrounded_in?(*chars) }
if replace_surrounding_chars
selected = selected[1..-2]
else
old_selection.last.column += (selected.include?("\n") ? 1 : 2)
end
insert("#{open_char}#{selected}#{close_char}")
@selection = old_selection
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/command_bar.rb | lib/ruco/command_bar.rb | module Ruco
class CommandBar
attr_accessor :cursor_line, :form
delegate :move, :delete, :insert, :selecting, :selection, :text_in_selection, :to => :form
SHORTCUTS = [
'^W Exit',
'^S Save',
'^F Find',
'^R Replace',
'^D Delete line',
'^G Go to line',
'^B Select mode'
]
def initialize(options)
@options = options
@forms_cache = {}
reset
end
def view
if @form
@form.view
else
available_shortcuts
end
end
def style_map
if @form
map = @form.style_map
map.invert!
map.prepend(:reverse, 0, 0..@options[:columns])
map
else
Dispel::StyleMap.single_line_reversed(@options[:columns])
end
end
def ask(question, options={}, &block)
@form = cached_form_if(options[:cache], question) do
Form.new(question, :columns => @options[:columns], :auto_enter => options[:auto_enter]) do |result|
@form = nil
block.call(result)
end
end
end
def reset
@forms_cache[@forms_cache.key(@form)] = nil
@form = nil
end
def cursor
if @form
Position.new cursor_line, @form.cursor.column
else
Position.new cursor_line, 0
end
end
private
def cached_form_if(cache, question)
if cache
new_form = yield
if @forms_cache[question]
new_form.insert(@forms_cache[question].value)
new_form.move(:to, 0,0)
new_form.selecting{ move(:to_eol) }
end
@forms_cache[question] = new_form
else
yield
end
end
def available_shortcuts
used_columns = 0
spacer = ' '
shortcuts_that_fit = SHORTCUTS.select do |shortcut|
used_columns += shortcut.size
it_fits = (used_columns <= @options[:columns])
used_columns += spacer.size
it_fits
end
shortcuts_that_fit * spacer
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/position.rb | lib/ruco/position.rb | module Ruco
class Position < Array
def initialize(line, column)
super([line, column])
end
def line=(x)
self[0] = x
end
def column=(x)
self[1] = x
end
alias_method :line, :first
alias_method :column, :last
end
end | ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/editor.rb | lib/ruco/editor.rb | module Ruco
class Editor
attr_reader :file
attr_reader :text_area
attr_reader :history
private :text_area
delegate :view, :style_map, :cursor, :position,
:insert, :indent, :unindent, :delete, :delete_line,
:redo, :undo, :save_state,
:selecting, :selection, :text_in_selection, :reset,
:move, :resize, :move_line,
:to => :text_area
def initialize(file, options)
@file = file
@options = options
handle = (File.exist?(file) ? File.open(file, 'rb') : nil)
# check for size (10000 lines * 100 chars should be enough for everybody !?)
if handle&.size.to_i > 1024 * 1024
raise "#{@file} is larger than 1MB, did you really want to open that with Ruco?"
end
content = handle&.read || ''
@options[:language] ||= LanguageSniffer.detect(@file, content: content).language
content.tabs_to_spaces! if @options[:convert_tabs]
# cleanup newline formats
@newline = content.match("\r\n|\r|\n")
@newline = (@newline ? @newline[0] : "\n")
content.gsub!(/\r\n?/,"\n")
@saved_content = content
@text_area = EditorArea.new(content, @options)
@history = @text_area.history
restore_session
# git and kubectl wait for the file to be closed, so give them that event
at_exit { handle&.close }
end
def find(text)
move(:relative, 0,0) # reset selection
start = text_area.content.index(text, text_area.index_for_position+1)
return unless start
# select the found word
finish = start + text.size
move(:to_index, finish)
selecting{ move(:to_index, start) }
true
end
def modified?
@saved_content != text_area.content
end
def save
lines = text_area.send(:lines)
lines.each(&:rstrip!) if @options[:remove_trailing_whitespace_on_save]
lines << '' if @options[:blank_line_before_eof_on_save] and lines.last.to_s !~ /^\s*$/
content = lines * @newline
File.open(@file,'wb'){|f| f.write(content) }
@saved_content = content.gsub(/\r?\n/, "\n")
true
rescue Object => e
e.message
end
def store_session
session_store.set(@file, text_area.state.slice(:position, :screen_position))
end
def content
text_area.content.freeze # no modifications allowed
end
private
def restore_session
if state = session_store.get(@file)
text_area.state = state
end
end
def session_store
FileStore.new(File.expand_path('~/.ruco/sessions'), :keep => 20)
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/tm_theme.rb | lib/ruco/tm_theme.rb | require 'plist'
module Ruco
class TMTheme
attr_accessor :background, :foreground, :styles
# TODO maybe later...
#attr_accessor :name, :uuid, :comment, :line_highlight
# not supported in Curses ...
#attr_accessor :invisibles, :caret, :selection
def initialize(file)
raw = Plist.parse_xml(file)
raise "Theme not found in #{file}" unless raw
rules = raw['settings']
@styles = {}
# set global styles
global = rules.shift['settings']
self.background = global['background']
self.foreground = global['foreground']
# set scope styles
rules.each do |rules|
style = [
rules['settings']['foreground'],
rules['settings']['background'],
]
next if style == [nil, nil] # some weird themes have rules without colors...
next unless scope = rules['scope'] # some weird themes have rules without scopes...
scope.split(/, ?/).map(&:strip).each do |scope|
@styles[scope] = style unless nested_scope?(scope)
end
end
end
private
def nested_scope?(scope)
scope.include?(' ')
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/syntax_parser.rb | lib/ruco/syntax_parser.rb | module Ruco
module SyntaxParser
# textpow only offers certain syntax
TEXTPOW_CONVERT = {
'html+erb' => 'text.html.ruby',
'rhtml' => 'text.html.ruby',
}
def self.syntax_for_line(line, languages)
syntax_for_lines([line], languages).first
end
cmemoize :syntax_for_line
def self.syntax_for_lines(lines, languages)
if syntax = syntax_node(languages)
begin
processor = syntax.parse(lines.join("\n"), Ruco::ArrayProcessor.new)
processor.lines
rescue RegexpError, ArgumentError
$stderr.puts $!
[]
end
else
[]
end
end
def self.syntax_node(languages)
found = nil
fallbacks = languages.map{|l| TEXTPOW_CONVERT[l] }.compact
(languages + fallbacks).detect do |language|
found = Textpow.syntax(language)
end
found
end
cmemoize :syntax_node
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/history.rb | lib/ruco/history.rb | module Ruco
class History
attr_accessor :timeout
attr_reader :stack, :position
def initialize(options)
@options = options
@options[:entries] ||= 100
@timeout = options.delete(:timeout) || 0
@stack = [{:mutable => false, :created_at => 0, :type => :initial, :state => @options.delete(:state)}]
@position = 0
end
def state
@stack[@position][:state]
end
def add(state)
return unless tracked_field_changes?(state)
remove_undone_states
unless merge? state
# can no longer modify previous states
@stack[@position][:mutable] = false
state_type = type(state)
@position += 1
@stack[@position] = {:mutable => true, :type => state_type, :created_at => Time.now.to_f}
end
@stack[@position][:state] = state
limit_stack
end
def undo
@position = [@position - 1, 0].max
end
def redo
@position = [@position + 1, @stack.size - 1].min
end
private
def type(state)
@options[:track].each do |field|
if state[field].is_a?(String) && @stack[@position][:state][field].is_a?(String)
diff = state[field].length - @stack[@position][:state][field].length
if diff > 0
return :insert
elsif diff < 0
return :delete
end
end
end
nil
end
def merge?(state)
top = @stack[@position]
top[:mutable] &&
top[:type] == type(state) &&
top[:created_at]+@timeout > Time.now.to_f
end
def remove_undone_states
@stack.slice!(@position + 1, 9999999)
end
def tracked_field_changes?(data)
@options[:track].any? do |field|
state[field] != data[field]
end
end
def limit_stack
return if @options[:entries] == 0
to_remove = @stack.size - @options[:entries]
return if to_remove < 1
@stack.slice!(0, to_remove)
@position -= to_remove
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/file_store.rb | lib/ruco/file_store.rb | require "digest/md5"
require "fileutils"
require "ruco/core_ext/file"
module Ruco
class FileStore
def initialize(folder, options={})
@folder = File.expand_path(folder)
@options = options
end
def set(key, value)
FileUtils.mkdir_p @folder unless File.exist? @folder
File.write(file(key), serialize(value))
cleanup if @options[:keep]
end
def get(key)
file = file(key)
deserialize File.binary_read(file) if File.exist?(file)
end
def cache(key, &block)
value = get(key)
if value.nil?
value = yield
set(key, value)
end
value
end
def delete(key)
FileUtils.rm(file(key))
rescue Errno::ENOENT
end
def clear
FileUtils.rm_rf(@folder)
end
def file(key)
"#{@folder}/#{Digest::MD5.hexdigest(key)}.yml"
end
private
def entries
(Dir.entries(@folder) - ['.','..']).
map{|entry| File.join(@folder, entry) }.
sort_by{|file| File.mtime(file) }
end
def cleanup
delete = entries[0...-@options[:keep]] || []
delete.each{|f| File.delete(f) }
end
def serialize(value)
@options[:string] ? value : Marshal.dump(value)
end
def deserialize(value)
@options[:string] ? value : Marshal.load(value)
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/option_accessor.rb | lib/ruco/option_accessor.rb | module Ruco
# Can be used like a hash, but also allows .key access
class OptionAccessor
attr_reader :wrapped
delegate :[], :[]=, :slice, :to => :wrapped
def initialize(wrapped={})
@wrapped = wrapped
end
def nested(key)
Hash[wrapped.map do |k,v|
if k.to_s =~ /^#{key}_(.*)$/
[$1.to_sym,v]
end
end.compact]
end
def method_missing(method, *args)
base = method.to_s.sub('=','').to_sym
raise if args.size != 1
@wrapped[base] = args.first
end
end
end | ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/editor/line_numbers.rb | lib/ruco/editor/line_numbers.rb | module Ruco
class Editor
module LineNumbers
LINE_NUMBERS_SPACE = 5
def initialize(content, options)
options[:columns] -= LINE_NUMBERS_SPACE if options[:line_numbers]
super(content, options)
end
def view
if @options[:line_numbers]
number_room = LINE_NUMBERS_SPACE - 1
super.naive_split("\n").map_with_index do |line,i|
number = @window.top + i
number = if lines[number]
(number + 1).to_s
else
''
end.rjust(number_room).slice(0,number_room)
"#{number} #{line}"
end * "\n"
else
super
end
end
def style_map
if @options[:line_numbers]
map = super
map.left_pad!(LINE_NUMBERS_SPACE)
map
else
super
end
end
def cursor
if @options[:line_numbers]
cursor = super
cursor[1] += LINE_NUMBERS_SPACE
cursor
else
super
end
end
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/editor/colors.rb | lib/ruco/editor/colors.rb | require 'timeout'
module Ruco
class Editor
module Colors
DEFAULT_THEME = File.expand_path('../../../../spec/fixtures/railscasts.tmTheme',__FILE__)
STYLING_TIMEOUT = 4
def style_map
$ruco_screen && $ruco_screen.options[:foreground] = theme.foreground
$ruco_screen && $ruco_screen.options[:background] = theme.background
map = super
return map if @colors_took_too_long or not @options[:language]
# disable colors if syntax-parsing takes too long
begin
syntax = Timeout.timeout(STYLING_TIMEOUT) do
syntax_info[@window.visible_lines]
end
rescue Timeout::Error
# this takes too long, just go on without styles
STDERR.puts "Styling takes too long, go on without me!"
@colors_took_too_long = true
return map
end
if syntax
add_syntax_highlighting_to_style_map(map, syntax)
# add selection a second time so it stays on top
@window.add_selection_styles(map, @selection) if @selection
end
map
end
private
def syntax_info
language = @options[:language]
possible_languages = [language.name.downcase, language.lexer]
lines.map do |line|
SyntaxParser.syntax_for_line(line, possible_languages)
end
end
def add_syntax_highlighting_to_style_map(map, syntax_info)
syntax_info.each_with_index do |syntax_positions, line|
next unless syntax_positions
syntax_positions.each do |syntax_element, columns|
next unless style = style_for_syntax_element(syntax_element)
next unless columns = adjust_columns_to_window_position(columns, @window.left)
map.add(style, line, columns)
end
end
end
def adjust_columns_to_window_position(columns, left)
return columns if left == 0
# style is out of scope -> add nothing
return nil if columns.max <= left
# shift style to the left
first = [0, columns.first - left].max
last = columns.max - left
first..last
end
def style_for_syntax_element(syntax_element)
_, style = theme.styles.detect{|name,style| syntax_element.start_with?(name) }
style
end
memoize :style_for_syntax_element
def theme
file = download_into_file(@options[:color_theme]) if @options[:color_theme]
file ||= DEFAULT_THEME
Ruco::TMTheme.new(file)
end
memoize :theme
def download_into_file(url)
theme_store = FileStore.new('~/.ruco/cache', string: true)
theme_store.cache(url) do
require 'open-uri'
require 'openssl'
OpenURI.without_ssl_verification do
URI.open(url).read
end
end
File.expand_path(theme_store.file(url))
rescue => e
STDERR.puts "Could not download #{url} set via :color_theme option -- #{e}"
end
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/editor/history.rb | lib/ruco/editor/history.rb | module Ruco
class Editor
module History
attr_reader :history
def initialize(content, options)
super(content, options)
@history = Ruco::History.new((options[:history]||{}).reverse_merge(:state => state, :track => [:content], :entries => options[:undo_stack_size], :timeout => 2))
end
def undo
@history.undo
self.state = @history.state
end
def redo
@history.redo
self.state = @history.state
end
def view
@history.add(state)
super
end
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/core_ext/range.rb | lib/ruco/core_ext/range.rb | class Range
# http://stackoverflow.com/questions/699448/ruby-how-do-you-check-whether-a-range-contains-a-subset-of-another-range
def overlap?(other)
(first <= other.last) and (other.first <= last)
end
# (1..2).move(2) == (3..4)
def move(n)
if exclude_end?
(first + n)...(last + n)
else
(first + n)..(last + n)
end
end
end
| ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
grosser/ruco | https://github.com/grosser/ruco/blob/fb4943b0f554d8f68de6d047591bf882af62bb42/lib/ruco/core_ext/array.rb | lib/ruco/core_ext/array.rb | # http://snippets.dzone.com/posts/show/5119
class Array
def map_with_index!
each_with_index do |e, idx| self[idx] = yield(e, idx); end
end
def map_with_index(&block)
dup.map_with_index!(&block)
end
end
# TODO move this to cursor <-> use cursor for calculations
class Array
def between?(a,b)
self.>= a and self.<= b
end
def <(other)
(self.<=>other) == -1
end
def <=(other)
self.<(other) or self.==other
end
def >(other)
(self.<=>other) == 1
end
def >=(other)
self.>(other) or self.==other
end
end
# http://madeofcode.com/posts/74-ruby-core-extension-array-sum
class Array
def sum(method = nil, &block)
if block_given?
raise ArgumentError, "You cannot pass a block and a method!" if method
inject(0) { |sum, i| sum + yield(i) }
elsif method
inject(0) { |sum, i| sum + i.send(method) }
else
inject(0) { |sum, i| sum + i }
end
end
end | ruby | MIT | fb4943b0f554d8f68de6d047591bf882af62bb42 | 2026-01-04T17:44:33.904693Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.