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
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/type/any.rb
lib/bake/type/any.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. module Bake module Type # An ordered list of types. The first type to match the input is used. # # ```ruby # type = Bake::Type::Any(Bake::Type::String, Bake::Type::Integer) # ``` # class Any # Initialize the instance with an array of types. # @parameter types [Array] the array of types. def initialize(types) @types = types end # Create a copy of the current instance with the other type appended. # @parameter other [Type] the type instance to append. def | other self.class.new([*@types, other]) end # Whether any of the listed types is a composite type. # @returns [Boolean] true if any of the listed types is `composite?`. def composite? @types.any?{|type| type.composite?} end # Parse an input string, trying the listed types in order, returning the first one which doesn't raise an exception. # @parameter input [String] the input to parse, e.g. `"5"`. def parse(input) @types.each do |type| return type.parse(input) rescue # Ignore. end end # As a class type, accepts any value. def self.parse(value) value end # Generate a readable string representation of the listed types. def to_s "any of #{@types.join(', ')}" end end # An extension module which allows constructing `Any` types using the `|` operator. module Type # Create an instance of `Any` with the arguments as types. # @parameter other [Type] the alternative type to match. def | other Any.new([self, other]) end end # A type constructor. # # ```ruby # Any(Integer, String) # ``` # # See [Any.initialize](#Bake::Type::Any::initialize). # def self.Any(*types) Any.new(types) end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/type/boolean.rb
lib/bake/type/boolean.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require_relative "any" module Bake module Type module Boolean extend Type def self.composite? false end def self.parse(input) if input =~ /t(rue)?|y(es)?/i return true elsif input =~ /f(alse)?|n(o)?/i return false else raise ArgumentError, "Cannot coerce #{input.inspect} into boolean!" end end end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/type/string.rb
lib/bake/type/string.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require_relative "any" module Bake module Type module String extend Type def self.composite? false end def self.parse(input) input.to_s end end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/type/input.rb
lib/bake/type/input.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require_relative "any" module Bake module Type module Input extend Type def self.composite? false end def self.parse(input) case input when "-" return $stdin when IO, StringIO return input else File.open(input) end end end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/type/integer.rb
lib/bake/type/integer.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require_relative "any" module Bake module Type module Integer extend Type def self.composite? false end def self.parse(input) Integer(input) end end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/type/nil.rb
lib/bake/type/nil.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require_relative "any" module Bake module Type module Nil extend Type def self.composite? false end def self.parse(input) if input =~ /nil|null/i return nil else raise ArgumentError, "Cannot coerce #{input.inspect} into nil!" end end end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/type/hash.rb
lib/bake/type/hash.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require_relative "any" module Bake module Type class Hash include Type def initialize(key_type, value_type) @key_type = key_type @value_type = value_type end def composite? true end def parse(input) hash = {} input.split(",").each do |pair| key, value = pair.split(":", 2) key = @key_type.parse(key) value = @value_type.parse(value) hash[key] = value end return hash end end def self.Hash(key_type, value_type) Hash.new(key_type, value_type) end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/type/symbol.rb
lib/bake/type/symbol.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require_relative "any" module Bake module Type module Symbol extend Type def self.composite? false end def self.parse(input) input.to_sym end end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/command/top.rb
lib/bake/command/top.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require "samovar" require "console/terminal" require_relative "call" require_relative "list" module Bake module Command # The top level command line application. class Top < Samovar::Command self.description = "Execute tasks using Ruby." options do option "-h/--help", "Show help." option "-b/--bakefile <path>", "Override the path to the bakefile to use." option "-g/--gem <name>", 'Load the specified gem, e.g. "bake ~> 1.0".' do |value| gem(*value.split(/\s+/)) end end nested :command, { "call" => Call, "list" => List, }, default: "call" def terminal(output = self.output) terminal = Console::Terminal.for(output) terminal[:context] = terminal[:loader] = terminal.style(nil, nil, :bold) terminal[:command] = terminal.style(nil, nil, :bold) terminal[:description] = terminal.style(:blue) terminal[:key] = terminal[:opt] = terminal.style(:green) terminal[:req] = terminal.style(:red) terminal[:keyreq] = terminal.style(:red, nil, :bold) terminal[:keyrest] = terminal.style(:green) terminal[:parameter] = terminal[:opt] return terminal end def bakefile_path @options[:bakefile] || Dir.pwd end def context Context.load(self.bakefile_path) end def call if @options[:help] self.print_usage else @command.call end end end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/command/list.rb
lib/bake/command/list.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require "samovar" require "set" module Bake module Command # List all available commands. class List < Samovar::Command self.description = "List all available commands." one :pattern, "The pattern to filter tasks by." def format_parameters(parameters, terminal) parameters.each do |type, name| case type when :key name = "#{name}=" when :keyreq name = "#{name}=" when :keyrest name = "**#{name}" else name = name.to_s end terminal.print(:reset, " ") terminal.print(type, name) end end def format_recipe(recipe, terminal) terminal.print(:command, recipe.command) if parameters = recipe.parameters format_parameters(parameters, terminal) end end def print_scope(terminal, scope, printed: false) format_recipe = self.method(:format_recipe).curry scope.recipes.sort.each do |recipe| if @pattern and !recipe.command.include?(pattern) next end unless printed yield printed = true end terminal.print_line terminal.print_line("\t", format_recipe[recipe]) documentation = recipe.documentation documentation.description do |line| terminal.print_line("\t\t", :description, line) end documentation.parameters do |parameter| terminal.print_line("\t\t", :parameter, parameter[:name], :reset, " [", :type, parameter[:type], :reset, "] ", :description, parameter[:details] ) end end return printed end def call first = true terminal = @parent.terminal context = @parent.context context.registry.each do |loader| printed = false loader.each do |path| loader.scopes_for(path) do |scope| print_scope(terminal, scope, printed: printed) do terminal.print_line(:loader, loader) printed = true end end end if printed terminal.print_line end end end end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/command/call.rb
lib/bake/command/call.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require "samovar" require_relative "../registry" require_relative "../context" module Bake module Command # Execute one or more commands. class Call < Samovar::Command self.description = "Execute one or more commands." def bakefile @parent.bakefile end many :commands, "The commands & arguments to invoke.", default: ["default"], stop: false def format(output, value) if formatter = OUTPUT[output] formatter.call(value) end end def call context = @parent.context context.call(*@commands) do |recipe, last_result| if last_result and !recipe.output? context.lookup("output").call(input: last_result) end end end end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/format/ndjson.rb
lib/bake/format/ndjson.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2025, by Samuel Williams. require "json" module Bake module Format class NDJSON def self.input(file) new(file) end def self.output(file, value) value.each do |item| file.puts(JSON.generate(item)) end end def initialize(file) @file = file end attr :file def each return to_enum unless block_given? @file.each_line do |line| yield JSON.parse(line) end end end REGISTRY[:ndjson] = NDJSON end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/format/yaml.rb
lib/bake/format/yaml.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2025, by Samuel Williams. require "yaml" module Bake module Format module YAML def self.input(file) ::YAML.load(file) end def self.output(file, value) ::YAML.dump(value, file) end end REGISTRY[:yaml] = YAML end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/format/raw.rb
lib/bake/format/raw.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2025, by Samuel Williams. require "pp" module Bake module Format module Raw def self.input(file) file end def self.output(file, value) PP.pp(value, file) end end REGISTRY[:raw] = Raw end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/format/json.rb
lib/bake/format/json.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2025, by Samuel Williams. require "json" module Bake module Format module JSON def self.input(file) ::JSON.load(file) end OPTIONS = {indent: " ", space: " ", space_before: "", object_nl: "\n", array_nl: "\n"} def self.output(file, value) ::JSON::State.generate(value, OPTIONS, file) file.puts end end REGISTRY[:json] = JSON end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/registry/bakefile_loader.rb
lib/bake/registry/bakefile_loader.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2024-2025, by Samuel Williams. require_relative "../scope" module Bake module Registry class BakefileLoader def initialize(path) @path = path end def to_s "#{self.class} #{@path}" end attr :path def each(&block) yield [] end def scopes_for(path) if path == [] yield Scope.load(@path, []) end end end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/registry/directory_loader.rb
lib/bake/registry/directory_loader.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require_relative "../scope" module Bake module Registry # Represents a directory which contains bakefiles. class DirectoryLoader # Initialize the loader with the specified root path. # @parameter root [String] A file-system path. def initialize(root, name: nil) @root = root @name = name end def to_s "#{self.class} #{@name || @root}" end # The root path for this loader. attr :root # Enumerate all bakefiles within the loaders root directory. # # You can pass the yielded path to {scope_for} to load the corresponding {Scope}. # # @yields {|path| ...} # @parameter path [String] The (relative) scope path. def each return to_enum unless block_given? Dir.glob("**/*.rb", base: @root) do |file_path| yield file_path.sub(/\.rb$/, "").split(File::SEPARATOR) end end # Load the {Scope} for the specified relative path within this loader, if it exists. # @parameter path [Array(String)] A relative path. def scopes_for(path) *directory, file = *path file_path = File.join(@root, directory, "#{file}.rb") if File.exist?(file_path) yield Scope.load(file_path, path) end end end class FileLoader def initialize(paths) @paths = paths end def to_s "#{self.class} #{@paths}" end attr :paths def each(&block) @paths.each_key(&block) end def scope_for(path) if file_path = @paths[path] if File.exist?(file_path) return Scope.load(file_path, path) end end end end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/registry/aggregate.rb
lib/bake/registry/aggregate.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require "console" require_relative "directory_loader" require_relative "bakefile_loader" module Bake # Structured access to the working directory and loaded gems for loading bakefiles. module Registry class Aggregate include Enumerable # Create a loader using the specified working directory. # @parameter working_directory [String] def self.default(working_directory, bakefile_path = nil) registry = self.new if bakefile_path registry.append_bakefile(bakefile_path) end registry.append_defaults(working_directory) return registry end # Initialize an empty array of registry. def initialize # Used to de-duplicated directories: @roots = {} # The ordered list of loaders: @ordered = Array.new end # Whether any registry are defined. # @returns [Boolean] def empty? @ordered.empty? end # Enumerate the registry in order. def each(&block) @ordered.each(&block) end def scopes_for(path, &block) @ordered.each do |registry| registry.scopes_for(path, &block) end end def append_bakefile(path) @ordered << BakefileLoader.new(path) end # Append a specific project path to the search path for recipes. # The computed path will have `bake` appended to it. # @parameter current [String] The path to add. def append_path(current = Dir.pwd, **options) bake_path = File.join(current, "bake") if File.directory?(bake_path) return insert(bake_path, **options) end return false end # Add registry according to the current working directory and loaded gems. # @parameter working_directory [String] def append_defaults(working_directory) # Load recipes from working directory: self.append_path(working_directory) # Load recipes from loaded gems: self.append_from_gems end # Enumerate all loaded gems and add them. def append_from_gems ::Gem.loaded_specs.each do |name, spec| Console.debug(self) {"Checking gem #{name}: #{spec.full_gem_path}..."} if path = spec.full_gem_path and File.directory?(path) append_path(path, name: spec.full_name) end end end protected def insert(directory, **options) unless @roots.key?(directory) Console.debug(self) {"Adding #{directory.inspect}"} loader = DirectoryLoader.new(directory, **options) @roots[directory] = loader @ordered << loader return true end return false end end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/config/sus.rb
config/sus.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2023-2025, by Samuel Williams. require "covered/sus" include Covered::Sus
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/features/support/env.rb
features/support/env.rb
$LOAD_PATH.unshift(File.dirname(__FILE__) + '/../../lib') require 'sonia' require 'spec/expectations'
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/features/step_definitions/sonia_steps.rb
features/step_definitions/sonia_steps.rb
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/widgets/yahoo_weather/yahoo_weather.rb
widgets/yahoo_weather/yahoo_weather.rb
module Sonia module Widgets class YahooWeather < Sonia::Widget URL = "http://weather.yahooapis.com/forecastrss?w=%s&u=%s" def initialize(config) super(config) EventMachine::add_periodic_timer(60 * 15) { fetch_data } end def initial_push fetch_data end private def fetch_data log_info "Polling `#{service_url}'" http = EventMachine::HttpRequest.new(service_url).get http.errback { log_fatal_error(http) } http.callback { handle_fetch_data_response(http) } end def handle_fetch_data_response(http) if http.response_header.status == 200 parse_response(http.response) else log_unsuccessful_response_body(http.response) end end def parse_response(response) payload = {} xml = parse_xml(response) location = xml.search("/rss/channel/yweather:location").first payload[:location] = {} [:city, :region, :country].each do |el| payload[:location][el] = location[el] end location = xml.search("/rss/channel/yweather:units").first payload[:units] = {} [:temperature, :distance, :pressure, :speed].each do |el| payload[:units][el] = location[el] end location = xml.search("/rss/channel/yweather:wind").first payload[:wind] = {} [:chill, :direction, :speed].each do |el| payload[:wind][el] = location[el] end location = xml.search("/rss/channel/yweather:atmosphere").first payload[:atmosphere] = {} [:humidity, :visibility, :pressure, :rising].each do |el| payload[:atmosphere][el] = location[el] end location = xml.search("/rss/channel/yweather:astronomy").first payload[:astronomy] = {} [:sunrise, :sunset].each do |el| payload[:astronomy][el] = location[el] end location = xml.search("/rss/channel/item/yweather:forecast") payload[:forecast] = [] location.each do |element| [:day, :date, :low, :high, :text, :code].each do |el| forecast = {} forecast[el] = element[el] payload[:forecast] << forecast end end payload[:image] = xml.search("/rss/channel/item/description").text.match(/<img src=\"(.*)\"\/>/)[1] payload[:lat] = xml.search("/rss/channel/item/geo:lat").first.text payload[:long] = xml.search("/rss/channel/item/geo:long").first.text location = xml.search("/rss/channel/item/yweather:condition").first payload[:condition] = {} [:text, :code, :temp, :date].each do |el| payload[:condition][el] = location[el] end push payload rescue => e log_backtrace(e) end def service_url URL % [config.woeid, config.units == "celsius" ? "c" : "f"] end end end end
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/widgets/hoptoad/hoptoad.rb
widgets/hoptoad/hoptoad.rb
require 'roxml' module Sonia module Widgets # ROXML classes doesn't include all stuff that Hoptoad returns # since we dont need it : we already have the api key and we # only need to count the total of errors for each projects # ROXML Projects class class Project include ROXML xml_accessor :id xml_accessor :name end class Projects include ROXML xml_accessor :projects, :as => [Project] end # ROXML Errors class class Group include ROXML xml_accessor :project_id, :from => "@project-id" xml_accessor :resolved end class Groups include ROXML xml_accessor :groups, :as => [Group] end class Hoptoad < Sonia::Widget PROJECTS_URL = "http://%s.hoptoadapp.com/projects.xml?auth_token=%s" # SSL redirecto to non-ssl url PROJECT_ERRORS_URL = "http://%s.hoptoadapp.com/errors.xml?auth_token=%s&project_id=%s" # same def initialize(config) super(config) @projects = [] EventMachine::add_periodic_timer(60 * 5) { fetch_data } end def initial_push fetch_data end private def fetch_data fetch_projects do fetch_errors end end def fetch_projects(&blk) log_info "Polling `#{projects_url}'" http = EventMachine::HttpRequest.new(projects_url).get http.errback { log_fatal_error(http) } http.callback { handle_projects_response(http) blk.call } end def handle_projects_response(http) if http.response_header.status == 200 @projects = Projects.from_xml(http.response).projects.map { |p| { :id => p.id, :name => p.name } } else log_unsuccessful_response_body(http.response) end rescue => e log_backtrace(e) end def fetch_errors multi = EventMachine::MultiRequest.new @projects.each do |project| url = project_errors_url(project[:id]) log_info "Polling `#{url}'" multi.add(EventMachine::HttpRequest.new(url).get) end multi.errback { log_fatal_error(multi) } multi.callback { handle_errors_response(multi) } end def handle_errors_response(multi) errors = multi.responses[:succeeded].map do |response| begin error_p_id = response.instance_variable_get(:@uri).query.split("project_id=").last project = project(error_p_id) project[:errors] = Groups.from_xml(response.response).groups.size project rescue => e log_backtrace(e) end end push errors rescue => e log_backtrace(e) end def projects_url PROJECTS_URL % [config.account, config.auth_key] end def project_errors_url(project_id) PROJECT_ERRORS_URL % [config.account, config.auth_key, project_id] end def project(project_id) @projects.detect { |r| r[:id] == project_id } end end end end
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/widgets/tfl/tfl.rb
widgets/tfl/tfl.rb
module Sonia module Widgets class Tfl < Sonia::Widget URL = "http://api.tubeupdates.com/?method=get.status&lines=all&format=json" def initialize(config) super(config) EventMachine::add_periodic_timer(150) { fetch_data } end def initial_push fetch_data end def format_lines(line) { :status_requested => line["status_requested"], :id => line["id"], :name => line["name"], :status => line["status"], :messages => line["messages"].join("\n") } end private def fetch_data log_info "Polling `#{service_url}'" http = EventMachine::HttpRequest.new(service_url).get http.errback { log_fatal_error(http) } http.callback { handle_fetch_data_response(http) } end def handle_fetch_data_response(http) if http.response_header.status == 200 parse_response(http.response) else log_unsuccessful_response_body(http.response) end end def parse_response(response) lines = parse_json(response)["response"]["lines"].map do |line| format_lines(line) end push lines rescue => e log_backtrace(e) end def service_url URL end end end end
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/widgets/twitter/twitter.rb
widgets/twitter/twitter.rb
require 'twitter/json_stream' module Sonia module Widgets class Twitter < Sonia::Widget FRIENDS_URL = "http://api.twitter.com/1/statuses/friends/%s.json" CREATE_FRIENDSHIP_URL = "http://api.twitter.com/1/friendships/create/%s.json?follow=true" USER_LOOKUP_URL = "http://api.twitter.com/1/users/lookup.json?screen_name=%s" FRIENDS_TIMELINE_URL = "http://api.twitter.com/1/statuses/friends_timeline.json?count=%s" def initialize(config) super(config) manage_friends end def initial_push log_info "Polling `#{friends_timeline_url}'" http = EventMachine::HttpRequest.new(friends_timeline_url).get(headers) http.errback { log_fatal_error(http) } http.callback { handle_initial_push(http) } end private def connect_to_stream @stream = ::Twitter::JSONStream.connect( :path => "/1/statuses/filter.json", :content => "follow=#{@user_ids.join(',')}", :method => "POST", :auth => [config.username, config.password].join(':') ) @stream.each_item do |status| push format_status(parse_json(status)) end ensure log_info "Connected to stream #{@stream.inspect}" end def manage_friends log_info "Polling `#{friends_url}'" http = EventMachine::HttpRequest.new(friends_url).get(headers) http.errback { log_fatal_error(http) } http.callback { handle_friends_response(http) } rescue => e log_backtrace(e) end def handle_friends_response(http) if http.response_header.status == 200 friends_usernames = extract_friends(http.response) new_friends_to_follow = follow_usernames - friends_usernames follow_new_users(new_friends_to_follow) lookup_user_ids_for(follow_usernames) { connect_to_stream } else log_unsuccessful_response_body(http.response) end rescue => e log_backtrace(e) end def handle_initial_push(http) if http.response_header.status == 200 parse_json(http.response).reverse.each do |status| push format_status(status) end else log_unsuccessful_response_body(http.response) end rescue => e log_backtrace(e) end def follow_new_users(users) if users.any? log_info "Creating new friendships with #{users.join(", ")}" users.each do |user| url = create_friendship_url(user) log_info "Polling `#{url}'" http = EventMachine::HttpRequest.new(url).post(headers) http.errback { log_fatal_error(http) } http.callback { handle_follow_new_users_response(http, user) } end else log_info"No new friendships to create, already following #{follow_usernames.join(', ')}" end end def handle_follow_new_users_response(http, user) if http.response_header.status == 200 log_info "Created friendship with #{user}" else log_unsuccessful_response_body(http.response) end end def follow_usernames config.follow.split(',') end def extract_friends(response) parse_json(response).map { |user| user["screen_name"] } end def headers { :head => { 'Authorization' => [config.username, config.password] } } end def create_friendship_url(user) CREATE_FRIENDSHIP_URL % user end def friends_timeline_url FRIENDS_TIMELINE_URL % config.nitems end def friends_url FRIENDS_URL % config.username end def user_lookup_url(users) USER_LOOKUP_URL % users.join(',') end def lookup_user_ids_for(usernames, &block) url = user_lookup_url(follow_usernames) log_info "Polling `#{url}'" http = EventMachine::HttpRequest.new(url).get(headers) http.errback { log_fatal_error(http) } http.callback { handle_user_ids_response(http, block) } end def handle_user_ids_response(http, block) if http.response_header.status == 200 @user_ids = parse_json(http.response).map { |e| e["id"] } block.call else log_unsuccessful_response_body(http.response) end rescue => e log_backtrace(e) end # { # "in_reply_to_status_id":11025304529, # "text":"@weembow LOL 'I HATE EVERYTHING BUT ANGELA AND WEED' when the fuck did i do that hahahaha", # "place":null, # han "in_reply_to_user_id":26580764, # "source":"web", # "coordinates":null, # "favorited":false, # "contributors":null, # "geo":null, # "user":{ # "lang":"en", # "profile_background_tile":true, # "location":"minneapolis minnesota", # "following":null, # "profile_sidebar_border_color":"0d0d0d", # "profile_image_url":"http://a1.twimg.com/profile_images/734139740/26461_106304702728342_100000464390009_157589_7540067_n_normal.jpg", # "verified":false, # "geo_enabled":true, # "followers_count":56, # "friends_count":66, # "description":"SCUM FUCK EAT SHIT.", # "screen_name":"jewslaya", # "profile_background_color":"cadbba", # "url":"http://www.facebook.com/profile.php?ref=profile&id=100000464390009", # "favourites_count":0, # "profile_text_color":"262626", # "time_zone":"Central Time (US & Canada)", # "protected":false, # "statuses_count":3394, # "notifications":null, # "profile_link_color":"a61414", # "name":"delaney pain", # "profile_background_image_url": # "http://a1.twimg.com/profile_background_images/80655374/2370378327_10f7b17053_o.jpg", "created_at":"Tue Jul 21 18:18:40 +0000 2009", # "id":58872581, # "contributors_enabled":false, # "utc_offset":-21600, # "profile_sidebar_fill_color":"f5e180" # }, # "in_reply_to_screen_name":"weembow", # "id":11046874752, # "created_at":"Thu Mar 25 18:22:14 +0000 2010", # "truncated":false # } def format_status(status) { :text => status['text'], :user => status['user']['screen_name'], :profile_image_url => status['user']['profile_image_url'] } end end end end
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/widgets/github/github.rb
widgets/github/github.rb
module Sonia module Widgets class Github < Sonia::Widget REPOSITIORIES_URL = "http://github.com/api/v2/yaml/repos/show/%s" NETWORK_META_URL = "%s://github.com/%s/%s/network_meta" NETWORK_DATA_CHUNK_URL = "%s://github.com/%s/%s/network_data_chunk?nethash=%s" def initialize(config) super(config) @repositories = [] @nethashes = [] EventMachine::add_periodic_timer(60 * 5) { fetch_data } end def initial_push fetch_data end private def fetch_data fetch_repositories do fetch_nethashes do fetch_commits end end end def fetch_repositories(&blk) log_info "Polling `#{repositories_url}'" http = EventMachine::HttpRequest.new(repositories_url).get(auth_data) http.errback { log_fatal_error(http) } http.callback { handle_repositories_response(http) blk.call } end def handle_repositories_response(http) if http.response_header.status == 200 @repositories = parse_yaml(http.response)["repositories"] else log_unsuccessful_response_body(http.response) end rescue => e log_backtrace(e) end def fetch_nethashes(&blk) multi = EventMachine::MultiRequest.new @repositories.each do |repo| url = network_meta_url(repo[:name]) log_info "Polling `#{url}'" multi.add(EventMachine::HttpRequest.new(url).get(auth_data)) end multi.errback { log_fatal_error(multi) } multi.callback { handle_nethashes_response(multi) blk.call } end def handle_nethashes_response(multi) @nethashes = multi.responses[:succeeded].map do |response| begin if response.response_header.status == 200 payload = parse_json(response.response) nethash = payload["nethash"] repo = payload["users"].first["repo"] { :repo => repo, :nethash => nethash } else log_unsuccessful_response_body(response.response) nil end rescue => e log_backtrace(e) nil end end.compact rescue => e log_backtrace(e) end def fetch_commits multi = EventMachine::MultiRequest.new @nethashes.each do |nethash| url = network_data_chunk_url(nethash[:repo], nethash[:nethash]) log_info "Polling `#{url}'" multi.add(EventMachine::HttpRequest.new(url).get(auth_data)) end multi.errback { log_fatal_error(multi) } multi.callback { handle_commits_response(multi) } end def handle_commits_response(multi) require 'pp' commits = multi.responses[:succeeded].map do |response| begin nethash = response.instance_variable_get(:@uri).query.split("nethash=").last repo = repo_name_for_nethash(nethash) commits = parse_json(response.response)["commits"].map { |commit| commit["repository"] = repo commit } rescue => e log_backtrace(e) end end.flatten.compact.sort_by { |e| Time.parse(e["date"]) }.reverse[0...config.nitems] push commits rescue => e log_backtrace(e) end def auth_data { :query => { "login" => config.username, "token" => config.token }} end def repositories_url REPOSITIORIES_URL % config.username end def network_meta_url(repo) repository = repo(repo) is_private = repository[:private] ? 'https' : 'http' NETWORK_META_URL % [is_private, config.username, repo] end def network_data_chunk_url(repo, nethash) repository = repo(repo) is_private = repository[:private] ? 'https' : 'http' NETWORK_DATA_CHUNK_URL % [is_private, config.username, repo, nethash] end def repo(repo) @repositories.detect { |r| r[:name] == repo } end def repo_name_for_nethash(nethash) repo(@nethashes.detect { |r| r[:nethash] == nethash }[:repo]) end end end end
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/widgets/campfire/campfire.rb
widgets/campfire/campfire.rb
require 'twitter/json_stream' require 'uri' require 'digest/md5' module Sonia module Widgets class Campfire < Sonia::Widget GRAVATAR_URL = "http://www.gravatar.com/avatar/" TRANSCRIPT_URL = "%s/room/%s/transcript.json" attr_reader :room_uri def initialize(config) super(config) @users = {} @room_uri = URI.encode("#{config.url}/room/#{config.room_id}.json") user_info connect_to_stream EventMachine::add_periodic_timer(150) { user_info } end def initial_push log_info "Polling `#{transcript_url}'" http = EventMachine::HttpRequest.new(transcript_url).get(headers) http.errback { log_fatal_error(http) } http.callback { handle_initial_response(http) } end private def connect_to_stream @stream = ::Twitter::JSONStream.connect( :path => "/room/#{config.room_id}/live.json", :host => 'streaming.campfirenow.com', :auth => "#{config.token}:x" ) @stream.each_item do |message| json_message = parse_json(message) formatted = format_message(json_message) push formatted unless formatted.nil? end ensure log_info "Connected to stream #{@stream.inspect}" end def handle_initial_response(http) if http.response_header.status == 200 messages = parse_json(http.response)["messages"].select { |message| message["type"] == "TextMessage" } message_from = messages.size >= config.nitems ? messages.size - config.nitems : 0 messages[message_from..-1].each do |message| formatted = format_message(message) push formatted unless formatted.nil? end else log_unsuccessful_response_body(http.response) end rescue => e log_backtrace(e) end def format_message(message) if message['type'] == 'TextMessage' user = @users[message['user_id']] img = user.nil? ? '' : user_gravatar(user[:email]) name = user.nil? ? 'Unknown' : user[:name] return { :body => message['body'], :user => name, :avatar => img } end return nil end def user_info log_info "Polling `#{room_uri}'" http = EventMachine::HttpRequest.new(room_uri).get(headers) http.errback { log_fatal_error(http) } http.callback { handle_user_info_response(http) } end def handle_user_info_response(http) if http.response_header.status == 200 parse_json(http.response)['room']['users'].each do |user| @users[user['id']] = { :name => user['name'], :email => user['email_address'] } end else log_unsuccessful_response_body(http.response) end rescue => e log_backtrace(e) end def user_gravatar(email) email_digest = Digest::MD5.hexdigest(email) "#{GRAVATAR_URL}#{email_digest}?d=identicon" end def transcript_url TRANSCRIPT_URL % [config.url, config.room_id] end def headers { :head => { 'Authorization' => [config.token, "x"] } } end end end end
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/widgets/rss/rss.rb
widgets/rss/rss.rb
module Sonia module Widgets class RSS < Sonia::Widget def initialize(config) super(config) EventMachine::add_periodic_timer(config[:poll_time]) { fetch_data } end def initial_push fetch_data end private def fetch_data log_info "Polling `#{service_url}'" http = EventMachine::HttpRequest.new(service_url).get http.errback { log_fatal_error(http) } http.callback { handle_fetch_data_response(http) } end def handle_fetch_data_response(http) if http.response_header.status == 200 parse_response(http.response) else log_unsuccessful_response_body(http.response) end end def parse_response(response) items = Nokogiri::XML.parse(response).xpath(config[:xpath]).map{|t| t.content} log_info("RSS items: #{items}") push :items => items[0...config[:nitems]] rescue => e log_backtrace(e) end def service_url config[:url] end end end end
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/widgets/foursquare/foursquare.rb
widgets/foursquare/foursquare.rb
module Sonia module Widgets class Foursquare < Sonia::Widget CHECKINS_URL = "http://api.foursquare.com/v1/checkins.json" def initialize(config) super(config) EventMachine::add_periodic_timer(150) { fetch_data } end def initial_push fetch_data end def format_checkin(checkin) { :name => "#{checkin["user"]["firstname"]} #{checkin["user"]["lastname"]}", :avatar_url => checkin["user"]["photo"], :venue => checkin["venue"]["name"], :when => time_ago_in_words(Time.now - Time.parse(checkin["created"])) } end private def fetch_data log_info "Polling `#{CHECKINS_URL}'" http = EventMachine::HttpRequest.new(CHECKINS_URL).get(headers) http.errback { log_fatal_error(http) } http.callback { handle_fetch_data_response(http) } end def handle_fetch_data_response(http) if http.response_header.status == 200 parse_response(http.response) else log_unsuccessful_response_body(http.response) end end def parse_response(response) messages = [] parse_json(response)["checkins"][0..5].map do |checkin| messages << format_checkin(checkin) if checkin["venue"] end push messages rescue => e log_backtrace(e) end def headers { :head => { 'Authorization' => [config.username, config.password] } } end def time_ago_in_words(seconds) case seconds when 0..60 then "#{seconds.floor} seconds" when 61..3600 then "#{(seconds/60).floor} minutes" when 3601..86400 then "#{(seconds/3600).floor} hours" else "#{(seconds/86400).floor} days" end end end end end
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/widgets/icinga/icinga.rb
widgets/icinga/icinga.rb
require 'nokogiri' module Sonia module Widgets class Icinga < Sonia::Widget def initialize(config) super(config) EventMachine::add_periodic_timer(60) { fetch_data } end def initial_push fetch_data end def format_status(stat) { :count => stat.match(/(\d*)\s(\w*)/)[1], :status => stat.match(/(\d*)\s(\w*)/)[2] } end private def headers { :head => { 'Authorization' => [config.username, config.password] } } end def fetch_data log_info "Polling `#{service_url}'" http = EventMachine::HttpRequest.new(service_url).get(headers) http.errback { log_fatal_error(http) } http.callback { handle_fetch_data_response(http) } end def handle_fetch_data_response(http) if http.response_header.status == 200 statuses = Nokogiri::HTML(http.response).xpath("//td/a[contains(@class,'serviceHeader')]").map do |node| format_status(node.content) end push statuses else log_unsuccessful_response_body(http.response) end rescue => e log_backtrace(e) end def service_url config.url end end # class end # module end # module
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/spec/spec_helper.rb
spec/spec_helper.rb
$LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'sonia' require 'spec' require 'spec/autorun' Spec::Runner.configure do |config| end
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/spec/sonia/config_spec.rb
spec/sonia/config_spec.rb
require 'spec_helper' require 'sonia/config' describe Sonia::Config do describe "#new" do let(:data) {{ :name => 'Sonia', :nested => { :one => 1, :two => 2 } }} subject { Sonia::Config.new(data) } its(:name) { should == 'Sonia' } its(:nested) { should be_kind_of Sonia::Config } it "has nested data" do subject.nested.one.should == 1 subject.nested.two.should == 2 end end describe "#[]" do let(:data) {{ :name => 'Sonia' }} subject { Sonia::Config.new(data) } it "returns same data" do subject.name.should == 'Sonia' subject[:name].should == 'Sonia' subject["name"].should == 'Sonia' end end describe "#[]=" do let(:data) {{ :name => 'Sonia' }} subject { Sonia::Config.new(data) } it "allows updating data" do subject.name.should == 'Sonia' subject[:name] = "Piotr" subject.name.should == 'Piotr' subject[:name].should == 'Piotr' subject["name"].should == 'Piotr' subject["name"] = "John" subject.name.should == 'John' subject[:name].should == 'John' subject["name"].should == 'John' end end describe "#each" do let(:data) {{ :name => 'Sonia', :age => 21 }} subject { Sonia::Config.new(data) } it "returns enumerator" do subject.each.should be_kind_of(Enumerator) end it "allows to iterate over keys" do hash = {} subject.each do |k, v| hash[k] = v end hash.keys.size.should == 2 hash.values.size.should == 2 hash.keys.should include(:name) hash.keys.should include(:age) hash.values.should include(21) hash.values.should include('Sonia') end end describe "#to_hash" do let(:data) {{ "age" => 21 }} subject { Sonia::Config.new(data) } it "returns whole config data" do subject.to_hash.should == { :age => 21 } end end end
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/lib/sonia.rb
lib/sonia.rb
$LOAD_PATH.unshift File.expand_path(File.dirname(__FILE__)) require 'logger' require 'active_support' require 'sonia/version' # @author Piotr Usewicz module Sonia autoload :Server, 'sonia/server' autoload :Widget, 'sonia/widget' autoload :Widgets, 'sonia/widgets' autoload :WebServer, 'sonia/web_server' autoload :Config, 'sonia/config' autoload :Helpers, 'sonia/helpers' # Returns application logger # # @return [Logger] def self.log @logger ||= Logger.new(STDOUT) end # Returns expanded path to the root directory # # @return [String] expanded path to the root directory def self.root @@root ||= File.expand_path(File.join(File.dirname(__FILE__), '..')) end end
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/lib/sonia/version.rb
lib/sonia/version.rb
module Sonia VERSION = "0.0.1" end
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/lib/sonia/widgets.rb
lib/sonia/widgets.rb
module Sonia # Responsible for just namespacing widgets module Widgets Dir[File.join(Sonia.root, "/widgets/*/*.rb")].each do |file| #autoload File.basename(file, '.rb').classify.to_sym, file require file end end end
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/lib/sonia/helpers.rb
lib/sonia/helpers.rb
module Sonia module Helpers # Returns all available widgets with relative path recognized by the webserver # # @return [Array] Array of relalive widget Javascript paths def widget_javascripts Dir[Sonia.root + "/widgets/*/*.js"].map do |file| widget_name = File.basename(file, ".js") file.gsub(File.join(Sonia.root, "widgets"), "/javascripts") end end # Returns all available widget stylesheets with relative paths recognized by the webserver # # @return [Array] Array of relative widget CSS files def widget_stylesheets Dir[Sonia.root + "/widgets/*/*.css"].map do |file| widget_name = File.basename(file, ".css") file.gsub(File.join(Sonia.root, "widgets"), "/stylesheets") end end def websocket_host Sonia::Server.websocket_host end def websocket_port Sonia::Server.websocket_port end def websocket_url Sonia::Server.websocket_url end def system_javascripts %w( /vendor/swfobject.js /vendor/console.js /vendor/FABridge.js /vendor/web_socket.js /vendor/json2.js /vendor/prototype.js /vendor/effects.js /vendor/dragdrop.js /vendor/livepipe.js /vendor/window.js /vendor/resizable.js /vendor/cookie.js /javascripts/storage.js /javascripts/sonia.js /javascripts/dispatcher.js /javascripts/widget.js ) end def system_stylesheets %w( /blueprint/reset.css /blueprint/grid.css /stylesheets/sonia.css ) end end end
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/lib/sonia/web_server.rb
lib/sonia/web_server.rb
require 'sinatra' require 'haml' module Sonia # Sonia's Web Server # # Allows dynamically generating HTML pages # # @author Piotr Usewicz class WebServer < Sinatra::Base helpers Sonia::Helpers set :public, File.expand_path(File.dirname(__FILE__) + '/../../public') set :views, File.expand_path(File.dirname(__FILE__) + '/../../views') set :env, :production configure do set :haml, { :format => :html5, :attr_wrapper => %Q{"} } end get "/" do haml :index end get "/javascripts/:widget/*.js" do content_type 'application/javascript', :charset => 'utf-8' send_file File.join(Sonia.root, "widgets", params[:widget], params[:splat].first + ".js") end get "/stylesheets/:widget/*.css" do content_type 'text/css', :charset => 'utf-8' send_file File.join(Sonia.root, "widgets", params[:widget], params[:splat].first + ".css") end get "/images/:widget/*.*" do send_file File.join(Sonia.root, "widgets", params[:widget], "images", params[:splat].join('.')) end end end
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/lib/sonia/cli.rb
lib/sonia/cli.rb
require 'thor' require "launchy" module Sonia class CLI < Thor # namespace nil desc "start", "Start Sonia server" method_option :config, :type => :string, :aliases => "-c", :required => true method_option :'no-auto', :type => :boolean def start require "sonia" Sonia::Server.run!(Config.new(options)) do Launchy.open(Sonia::Server.webserver_url) unless options[:'no-auto'] end end desc "console", "Start Sonia console" def console ARGV.pop # Remove console as parameter require 'irb' require 'irb/completion' require 'sonia' IRB.start(__FILE__) end desc "version", "Prints Sonia's version information" def version require 'sonia/version' puts "Sonia v#{Sonia::VERSION}" end map %w(-v --version) => :version end end
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/lib/sonia/widget.rb
lib/sonia/widget.rb
require "yajl" require "yaml" require "nokogiri" require "digest/sha1" module Sonia # @abstract class Widget class << self def inherited(subclass) (@widgets ||= []) << subclass unless widgets.include?(subclass) end def widgets @widgets ||= [] end end attr_reader :widget_id, :channel, :sid, :config, :log # Initalizes the widget # # @param [Hash] config Configuration of the widget from the config file def initialize(config) @log = Sonia.log @channel = EM::Channel.new @config = config || Config.new({}) @widget_id = Digest::SHA1.hexdigest([ @config.to_hash.keys.map { |s| s.to_s }.sort.join, @config.to_hash.values.map { |s| s.to_s }.sort.join, self.class ].join) end # Returns JSON encode # # @return [Yajl::Encoder] def encoder @encoder ||= Yajl::Encoder.new end # Returns JSON parser # # @return [Yajl::Parser] def parser @decoder ||= Yajl::Parser.new end # Parses JSON # # @param [String] payload JSON string # @return [Hash] Parsed JSON represented as a hash def parse_json(payload) Yajl::Parser.parse(payload) end # Parses YAML # # @param [String] payload YAML string # @return [Hash] Parsed YAML represented as a hash def parse_yaml(payload) YAML.load(payload) end # Parse XML # # @param [String] payload XML string # @return [Nokogiri::XML::Document] Parsed Nokogiri document def parse_xml(payload) Nokogiri(payload) end # Used to push initial data after setup #def initial_push; end # Subscribes a websocket to widget's data channel # # @param [EventMachine::WebSocket] websocket # @return [String] Subscriber ID def subscribe!(websocket) @sid = channel.subscribe { |msg| websocket.send msg } ensure log.info(widget_name) { "Subscribed #{sid} via #{channel}" } end # Unsubscribes a subscriber id from data channel def unsubscribe! channel.unsubscribe(sid) ensure log.info(widget_name) { "Unsubscribed #{sid} via #{channel}" } end # Pushes data to the channel # # @param [Hash] msg Data which can be JSONified def push(msg) payload = { :payload => msg, :widget => self.widget_name, :widget_id => self.widget_id } message = { :message => payload } channel.push self.encoder.encode(message) ensure log.info(widget_name) { "Pushing #{message.inspect} via #{channel}" } end # Returns widget name # # @return [String] Name of the widget def widget_name self.class.name.split("::").last end # Initial widget setup data that gets pushed to the client # # @return [Hash] Initial widget information and configuration def setup { :widget => self.widget_name, :widget_id => self.widget_id, :config => self.config.to_hash } end def log_unsuccessful_response_body(response_body) log.warn(widget_name) { "Bad response: #{response_body.inspect}" } end def log_fatal_error(http) log.fatal(widget_name) { http.inspect } end def log_backtrace(exception) log.fatal(widget_name) { [exception.message, exception.backtrace].join("\n") } end def log_info(message) log.info(widget_name) { message } end end end
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/lib/sonia/config.rb
lib/sonia/config.rb
module Sonia # Simple configuration class # # @example # "Config.new({:name => "Piotr"}).piotr" #=> "Piotr" class Config # @param [Hash] data Hash containing configuration data def initialize(data={}) @data = {} update!(data) end # Updates configuration data # # @param [Hash] data def update!(data) data.each do |key, value| self[key] = value end end # Returns configuration value # # @param [#to_sym] key Key of the value def [](key) @data[key.to_sym] end # Allows setting a value # # @param [#to_sym] key Key of the value # @param [Object] value Configuration value def []=(key, value) if value.class == Hash @data[key.to_sym] = Config.new(value) else @data[key.to_sym] = value end end # Returns each configuration key - value pair or an iterator # # @yield [key, value] # @param [Enumerator] def each if block_given? @data.each do |k, v| yield k, v end else @data.each end end # Returns configuration value by missing method name # # @param [Symbol] sym Key name as symbol # @return [Object] def method_missing(sym, *args) if sym.to_s =~ /(.+)=$/ self[$1] = args.first else self[sym] end end # Returns whole configuration data as hash # # @return [Hash] def to_hash @data end end end
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
pusewicz/sonia
https://github.com/pusewicz/sonia/blob/80e1a22b3f598d8bbac553380acc7c5a869b2143/lib/sonia/server.rb
lib/sonia/server.rb
require "eventmachine" require "em-websocket" require 'em-http' require "yajl" require "yaml" require "thin" module Sonia # Main Sonia event loop # # Starts both WebServer and WebSocket server # # @author Piotr Usewicz module Server extend self # Defaults WEBSOCKET_HOST = "localhost" WEBSOCKET_PORT = 8080 WEBSERVER_HOST = "localhost" WEBSERVER_PORT = 3000 # Starts the server # # @param [Hash] args Startup options def run!(args, &block) @start_block = block configure(args) serve end # Returns configuration from the config file # # @return [Config] def config @@config end # Loads the configuration file # # @param [Hash] options # @return [Config] def configure(options) @@config = Config.new(YAML.load_file(File.expand_path(options.config))) end # Returns [Logger] object # # @return [Logger] def log Sonia.log end # Starts main [EventMachine] loop def serve EventMachine.run { initialize_widgets start_web_socket_server start_web_server @start_block.call } end # Goes through configured widgets and initializes them def initialize_widgets @widgets = [] config.widgets.each do |widget, config| class_name = "Sonia::Widgets::#{widget.to_s}" log.info("Server") { "Created widget #{widget} with #{config.inspect}" } @widgets << module_eval(class_name).new(config) end end # Returns websocket configuration options # # @return [Hash] Websocket's host and port number def websocket_options { :host => websocket_host, :port => websocket_port } end # Returns configured websocket hostname # # @return [String] Websocket hostname def websocket_host config.websocket.host || WEBSOCKET_HOST end # Returns configured websocket port # # @return [String] Websocket port def websocket_port config.websocket.port || WEBSOCKET_PORT end # Starts WebSocket server def start_web_socket_server EventMachine::WebSocket.start(websocket_options) do |ws| ws.onopen { @widgets.map { |widget| widget.subscribe!(ws) } setup_message = { :setup => @widgets.map { |widget| widget.setup } } ws.send Yajl::Encoder.encode(setup_message) log.info("Server") { "Sent setup #{setup_message.inspect}" } @widgets.each { |widget| if widget.respond_to?(:initial_push) log.info(widget.widget_name) { "Sending initial push" } widget.initial_push end } } #ws.onmessage { |msg| #@widgets.each do |widget| #widget.push "<#{@sids}>: #{msg}" #end #} ws.onclose { @widgets.each { |widget| widget.unsubscribe! } } end log.info("Server") { "WebSocket Server running at #{websocket_options[:host]}:#{websocket_options[:port]}" } end # Starts Thin WebServer def start_web_server Thin::Server.start( webserver_host, webserver_port, ::Sonia::WebServer ) end # Returns configured webserver host # # @return [String] Webserver host def webserver_host config.webserver.host || WEBSERVER_HOST end # Returns configured webserver port # # @return [String] webserver port def webserver_port config.webserver.port || WEBSERVER_PORT end # Returns WebServer URL # # @return [String] WebServer URL def webserver_url "http://#{webserver_host}:#{webserver_port}" end # Returns WebSocket URL # # @return [String] WebSocket URL def websocket_url "ws://#{websocket_host}:#{websocket_port}" end end end
ruby
MIT
80e1a22b3f598d8bbac553380acc7c5a869b2143
2026-01-04T17:57:57.950848Z
false
sous-chefs/ruby_build
https://github.com/sous-chefs/ruby_build/blob/f4985daab9ac89b00771108ea8ac4fe18ae376e2/metadata.rb
metadata.rb
name 'ruby_build' maintainer 'Sous Chefs' maintainer_email 'help@sous-chefs.org' license 'Apache-2.0' description 'Manages the ruby-build framework and its installed rubies. A LWRP is also defined.' source_url 'https://github.com/sous-chefs/ruby_build' issues_url 'https://github.com/sous-chefs/ruby_build/issues' chef_version '>= 15.0' version '2.5.12' supports 'ubuntu' supports 'debian' supports 'freebsd' supports 'redhat' supports 'centos' supports 'fedora' supports 'amazon' supports 'scientific' supports 'suse' supports 'opensuse' supports 'opensuseleap' supports 'mac_os_x' depends 'yum-epel' depends 'homebrew'
ruby
Apache-2.0
f4985daab9ac89b00771108ea8ac4fe18ae376e2
2026-01-04T17:58:09.746881Z
false
sous-chefs/ruby_build
https://github.com/sous-chefs/ruby_build/blob/f4985daab9ac89b00771108ea8ac4fe18ae376e2/test/integration/default/controls/verify_ruby_build.rb
test/integration/default/controls/verify_ruby_build.rb
control 'Check definitions' do impact 1.0 title 'Verify we can return a list of definitions' desc 'Verify we can get a list of Ruby definitions' describe command('/usr/local/bin/ruby-build --definitions') do its('exit_status') { should eq 0 } its('stdout') { should match /3.0.4/ } end end control 'ruby-build binary should work' do impact 1.0 title 'Verify that running ruby-build works' desc 'Verify that running ruby-build will work for users' describe file('/usr/local/bin/ruby-build') do it { should be_file } it { should be_executable } end end gem_cmd = if os.darwin? 'sudo /usr/local/ruby/3.0.4/bin/gem install ffi --no-document' else '/usr/local/ruby/3.0.4/bin/gem install ffi --no-document' end control 'Install a Ruby gem' do impact 1.0 title 'Verify gem install works' desc 'Verify gem install works, and the gem works after installation' describe command(gem_cmd) do its('exit_status') { should eq 0 } its('stdout') { should match /Successfully installed ffi/ } end describe command('/usr/local/ruby/3.0.4/bin/gem env') do its('exit_status') { should eq 0 } its('stdout') { should match %r{gems/3.0.0} } end end
ruby
Apache-2.0
f4985daab9ac89b00771108ea8ac4fe18ae376e2
2026-01-04T17:58:09.746881Z
false
sous-chefs/ruby_build
https://github.com/sous-chefs/ruby_build/blob/f4985daab9ac89b00771108ea8ac4fe18ae376e2/test/cookbooks/test/metadata.rb
test/cookbooks/test/metadata.rb
name 'test' version '1.0.0' depends 'ruby_build'
ruby
Apache-2.0
f4985daab9ac89b00771108ea8ac4fe18ae376e2
2026-01-04T17:58:09.746881Z
false
sous-chefs/ruby_build
https://github.com/sous-chefs/ruby_build/blob/f4985daab9ac89b00771108ea8ac4fe18ae376e2/test/cookbooks/test/recipes/default.rb
test/cookbooks/test/recipes/default.rb
apt_update homebrew_update ruby_build_install ruby_build_definition '3.0.4' do version_prefix true patch 'test.patch' end
ruby
Apache-2.0
f4985daab9ac89b00771108ea8ac4fe18ae376e2
2026-01-04T17:58:09.746881Z
false
sous-chefs/ruby_build
https://github.com/sous-chefs/ruby_build/blob/f4985daab9ac89b00771108ea8ac4fe18ae376e2/spec/spec_helper.rb
spec/spec_helper.rb
require 'chefspec' require 'chefspec/berkshelf' require_relative '../libraries/package_deps' RSpec.configure do |config| config.color = true config.formatter = :documentation end
ruby
Apache-2.0
f4985daab9ac89b00771108ea8ac4fe18ae376e2
2026-01-04T17:58:09.746881Z
false
sous-chefs/ruby_build
https://github.com/sous-chefs/ruby_build/blob/f4985daab9ac89b00771108ea8ac4fe18ae376e2/spec/libraries/cruby_spec.rb
spec/libraries/cruby_spec.rb
require 'spec_helper' describe '#cruby_package_deps' do context 'CentOS' do recipe do Chef::DSL::Recipe.include(Chef::Rbenv::PackageDeps) log cruby_package_deps end context 'CentOS 7' do platform 'centos', '7' it { is_expected.to write_log('gcc, bzip2, openssl-devel, libyaml-devel, libffi-devel, readline-devel, zlib-devel, gdbm-devel, ncurses-devel, make, patch') } end context 'CentOS 8' do platform 'centos', '8' it { is_expected.to write_log('gcc, bzip2, openssl-devel, libyaml-devel, libffi-devel, readline-devel, zlib-devel, gdbm-devel, ncurses-devel, make, patch') } end context 'Debian 9' do platform 'debian', '9' it { is_expected.to write_log('gcc, autoconf, bison, build-essential, libssl-dev, libyaml-dev, libreadline6-dev, zlib1g-dev, libncurses5-dev, libffi-dev, libgdbm3, libgdbm-dev, make, patch') } end context 'Debian 10' do platform 'debian', '10' it { is_expected.to write_log('gcc, autoconf, bison, build-essential, libssl-dev, libyaml-dev, libreadline6-dev, zlib1g-dev, libncurses5-dev, libffi-dev, libgdbm6, libgdbm-dev, make, patch') } end context 'Ubuntu 16.04' do platform 'ubuntu', '16.04' it { is_expected.to write_log('gcc, autoconf, bison, build-essential, libssl-dev, libyaml-dev, libreadline6-dev, zlib1g-dev, libncurses5-dev, libffi-dev, libgdbm3, libgdbm-dev, make, patch') } end context 'Ubuntu 18.04' do platform 'ubuntu', '18.04' it { is_expected.to write_log('gcc, autoconf, bison, build-essential, libssl-dev, libyaml-dev, libreadline6-dev, zlib1g-dev, libncurses5-dev, libffi-dev, libgdbm5, libgdbm-dev, make, patch') } end context 'Ubuntu 20.04' do end end end
ruby
Apache-2.0
f4985daab9ac89b00771108ea8ac4fe18ae376e2
2026-01-04T17:58:09.746881Z
false
sous-chefs/ruby_build
https://github.com/sous-chefs/ruby_build/blob/f4985daab9ac89b00771108ea8ac4fe18ae376e2/libraries/package_deps.rb
libraries/package_deps.rb
class Chef module Rbenv module MacOs def openssl_prefix `/usr/local/bin/brew --prefix openssl@1.1`.strip! end end module PackageDeps def cruby_package_deps case node['platform_family'] when 'rhel', 'fedora', 'amazon' %w( gcc bzip2 openssl-devel libyaml-devel libffi-devel readline-devel zlib-devel gdbm-devel ncurses-devel make patch ) when 'debian' case node['platform'] when 'debian' if node['platform_version'].to_i >= 10 %w( gcc autoconf bison build-essential libssl-dev libyaml-dev libreadline6-dev zlib1g-dev libncurses5-dev libffi-dev libgdbm6 libgdbm-dev make patch ) else %w( gcc autoconf bison build-essential libssl-dev libyaml-dev libreadline6-dev zlib1g-dev libncurses5-dev libffi-dev libgdbm3 libgdbm-dev make patch ) end when 'ubuntu' if node['platform_version'].to_i >= 20 %w( gcc autoconf bison build-essential libssl-dev libyaml-dev libreadline6-dev zlib1g-dev libncurses5-dev libffi-dev libgdbm6 libgdbm-dev make patch ) elsif node['platform_version'].to_i == 18 %w( gcc autoconf bison build-essential libssl-dev libyaml-dev libreadline6-dev zlib1g-dev libncurses5-dev libffi-dev libgdbm5 libgdbm-dev make patch ) else %w( gcc autoconf bison build-essential libssl-dev libyaml-dev libreadline6-dev zlib1g-dev libncurses5-dev libffi-dev libgdbm3 libgdbm-dev make patch ) end end when 'suse' %w( gcc make automake gdbm-devel libyaml-devel ncurses-devel readline-devel zlib-devel libopenssl-devel patch ) when 'mac_os_x' %w( openssl@1.1 readline ) end end def package_deps cruby_package_deps end end end end
ruby
Apache-2.0
f4985daab9ac89b00771108ea8ac4fe18ae376e2
2026-01-04T17:58:09.746881Z
false
sous-chefs/ruby_build
https://github.com/sous-chefs/ruby_build/blob/f4985daab9ac89b00771108ea8ac4fe18ae376e2/resources/homebrew_update.rb
resources/homebrew_update.rb
unified_mode true if respond_to? :unified_mode provides :homebrew_update description 'Use the **homebrew_update** resource to manage Homebrew repository updates on MacOS.' introduced '16.2' examples <<~DOC **Update the hombrew repository data at a specified interval**: ```ruby homebrew_update 'all platforms' do frequency 86400 action :periodic end ``` **Update the Homebrew repository at the start of a Chef Infra Client run**: ```ruby homebrew_update 'update' ``` DOC # allow bare homebrew_update with no name property :name, String, default: '' property :frequency, Integer, description: 'Determines how frequently (in seconds) Homebrew updates are made. Use this property when the `:periodic` action is specified.', default: 86_400 default_action :periodic action_class do BREW_STAMP_DIR = '/var/lib/homebrew/periodic'.freeze BREW_STAMP = "#{BREW_STAMP_DIR}/update-success-stamp".freeze # Determines whether we need to run `homebrew update` # # @return [Boolean] def brew_up_to_date? ::File.exist?(BREW_STAMP) && ::File.mtime(BREW_STAMP) > Time.now - new_resource.frequency end def do_update directory BREW_STAMP_DIR do recursive true end file BREW_STAMP do content "BREW::Update::Post-Invoke-Success\n" action :create_if_missing end execute 'brew update' do command %w(brew update) default_env true user Homebrew.owner notifies :touch, "file[#{BREW_STAMP}]", :immediately end end end action :periodic do return unless mac_os_x? unless brew_up_to_date? converge_by 'update new lists of packages' do do_update end end end action :update do return unless mac_os_x? converge_by 'force update new lists of packages' do do_update end end
ruby
Apache-2.0
f4985daab9ac89b00771108ea8ac4fe18ae376e2
2026-01-04T17:58:09.746881Z
false
sous-chefs/ruby_build
https://github.com/sous-chefs/ruby_build/blob/f4985daab9ac89b00771108ea8ac4fe18ae376e2/resources/definition.rb
resources/definition.rb
include Chef::Rbenv::MacOs # for compatibility with earlier incarnations # of this resource # provides :ruby_build_ruby property :definition, String, name_property: true, description: 'Version of Ruby to install' property :prefix_path, String, default: '/usr/local/ruby', description: 'Location to install Ruby' property :verbose, [true, false], default: false, description: 'print compilation status to stdout' # NOTE: adding the Ruby version to the installation prefix # by default is unexpected and will likely lead to user # problems. Now defaults to false. # property :version_prefix, [true, false], default: false, description: 'add Ruby version to the installation prefix' property :patch, [String, nil], description: 'path to a Ruby patch file for ruby-build to use' property :environment, Hash, default: {}, description: 'Environment hash to pass to the ruby-build install process' property :user, String, description: 'User to install as' property :group, String, description: 'Group to install as' unified_mode true if respond_to? :unified_mode action :install do Chef::Log.fatal('JRuby is not a supported definition') \ if new_resource.definition.include? 'jruby' if platform_family?('mac_os_x') && Chef::VERSION < '16' Array(package_deps).each do |pkg| package pkg end else package package_deps end installation_path = if new_resource.version_prefix ::File.join(new_resource.prefix_path, new_resource.definition) else new_resource.prefix_path end env = if platform_family?('mac_os_x') extra_env = { 'RUBY_CONFIGURE_OPTS' => "--with-openssl-dir=#{openssl_prefix}" } new_resource.environment.merge extra_env else new_resource.environment end ruby_build_cmd = [ '/usr/local/bin/ruby-build', new_resource.definition, installation_path, ].join(' ') ruby_build_cmd += ' --verbose' if new_resource.verbose if new_resource.patch patch_path = "#{Chef::Config[:file_cache_path]}/#{new_resource.patch}" ruby_build_cmd += %( --patch < "#{patch_path}" ) cookbook_file patch_path do source new_resource.patch end end bash "ruby-build #{new_resource.definition}" do code ruby_build_cmd environment env user new_resource.user group new_resource.group not_if do ::Dir.exist?("#{installation_path}/bin") && new_resource.definition == `#{installation_path}/bin/ruby -e 'print RUBY_VERSION'` end live_stream true action :run end end action_class do include Chef::Rbenv::PackageDeps include Chef::Rbenv::MacOs end
ruby
Apache-2.0
f4985daab9ac89b00771108ea8ac4fe18ae376e2
2026-01-04T17:58:09.746881Z
false
sous-chefs/ruby_build
https://github.com/sous-chefs/ruby_build/blob/f4985daab9ac89b00771108ea8ac4fe18ae376e2/resources/install.rb
resources/install.rb
property :name, String, default: '' property :git_ref, String, default: 'master', description: 'Git reference to download, set to a tag to get a specific version' unified_mode true if respond_to? :unified_mode action :install do src_path = "#{Chef::Config['file_cache_path']}/ruby-build" if platform_family?('rhel') if node['platform_version'].to_i == 9 package 'yum-utils' execute 'yum-config-manager --enable crb' do not_if 'yum-config-manager --dump crb | grep -q "enabled = 1"' end elsif node['platform_version'].to_i == 8 package 'yum-utils' execute 'yum-config-manager --enable powertools' do not_if 'yum-config-manager --dump powertools | grep -q "enabled = 1"' end end include_recipe 'yum-epel' end package %w(tar bash curl git) unless platform_family?('mac_os_x', 'freebsd') git src_path do repository 'https://github.com/rbenv/ruby-build.git' revision new_resource.git_ref unless new_resource.git_ref == 'master' retries 5 retry_delay 5 end execute 'Install ruby-build' do cwd src_path command %(sh ./install.sh) not_if do ::File.exist?('/usr/local/bin/ruby-build') && `#{src_path}/bin/ruby-build --version` == `/usr/local/bin/ruby-build --version` end end end
ruby
Apache-2.0
f4985daab9ac89b00771108ea8ac4fe18ae376e2
2026-01-04T17:58:09.746881Z
false
dkeas/DManga
https://github.com/dkeas/DManga/blob/e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8/test/dmanga_test.rb
test/dmanga_test.rb
require 'dmanga' require_relative 'test_helper' class DMangaTest < Minitest::Test def test_that_it_has_a_version_number refute_nil ::DManga::VERSION end end
ruby
MIT
e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8
2026-01-04T17:58:07.727342Z
false
dkeas/DManga
https://github.com/dkeas/DManga/blob/e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8/test/test_helper.rb
test/test_helper.rb
# require 'minitest/reporters' require 'minitest/autorun' require 'minitest/pride' # MiniTest::Reporters.use!
ruby
MIT
e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8
2026-01-04T17:58:07.727342Z
false
dkeas/DManga
https://github.com/dkeas/DManga/blob/e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8/test/options_test.rb
test/options_test.rb
# require 'minitest/autorun' require 'dmanga/options' require_relative 'test_helper' class TestOption < Minitest::Test def test_options_manga_name opt = DManga::Options.new(['manga name']) assert_equal opt.manga, 'manga name' end def test_options_without_download_path opt = DManga::Options.new(['-v', 'manga name']) assert_equal DManga::Options::DEFAULT_DOWNLOAD_DIR, opt.download_dir end def test_options_all opt = DManga::Options.new(['-v', '-d', '/path/to/directory', 'manga another name']) assert_equal '/path/to/directory', opt.download_dir assert opt.verbose, 'verbose must be true' assert_equal opt.manga, 'manga another name' end def test_options_without_verbose opt = DManga::Options.new(['-d', '/path/to/directory', 'manga name']) refute opt.verbose, 'verbose must be false' end end
ruby
MIT
e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8
2026-01-04T17:58:07.727342Z
false
dkeas/DManga
https://github.com/dkeas/DManga/blob/e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8/test/zip_file_generator_test.rb
test/zip_file_generator_test.rb
require 'dmanga/zip_file_generator' class TestZipFileGenerator < Minitest::Test def test_put_into_archive out_file = "#{File.dirname(__FILE__)}/files/test.zip" in_dir = "#{File.dirname(__FILE__)}/files" zf = DManga::ZipFileGenerator.new(in_dir, out_file) zf.write assert File.exist? out_file FileUtils.rm out_file end end
ruby
MIT
e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8
2026-01-04T17:58:07.727342Z
false
dkeas/DManga
https://github.com/dkeas/DManga/blob/e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8/test/site_parser_base_test.rb
test/site_parser_base_test.rb
require 'webmock/minitest' require 'dmanga/site_parser_base' require 'dmanga/mangahost_parser' require 'dmanga/util' require_relative 'test_helper' class TestSiteParserBase < Minitest::Test SEARCH_PAGE = [ File.dirname(__FILE__), "files", "onepunch-search.html"].join("/") CHAPTER_PAGE = [ [File.dirname(__FILE__), "files", "onepunch-chapters.html"].join("/"), [File.dirname(__FILE__), "files", "tomo-chapters.html"].join("/") ] IMGS_PAGE = [ " ", [File.dirname(__FILE__), "files", "tokyoghoul-imgs.html"].join("/")] def setup @site_parser = DManga::SiteParserBase.new(["manga name"]) end def test_parse_search_page mangas = [ ["https://mangahost.net/manga/db-x-saitama-doujinshi", "DB X Saitama (Doujinshi)"], ["https://mangahost.net/manga/fire-punch", "Fire Punch"], ["https://mangahost.net/manga/one-punch-man", "One Punch-Man"], ["https://mangahost.net/manga/one-punch-man-one", "One Punch-Man (One)"], ["https://mangahost.net/manga/punch", "Punch!"], ["https://mangahost.net/manga/short-program-girls-type", "Short Program - Girl's Type"] ] page = File.open(SEARCH_PAGE).read stub_request(:get, "http://mangahost.net/find/one-punch"). to_return(status:[200, "OK"], body: page) result = @site_parser.parse("http://mangahost.net/find/one-punch", DManga::MangaHostParser::SEARCH_LINK_REGEX) assert_equal mangas, result end def test_parse_chapters_page_for_long_mangas # test only the first threes and last threes firsts = [['https://mangahost.net/manga/one-punch-man/3', 'Cap&iacute;tulo #3 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/2', 'Cap&iacute;tulo #2 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/1', 'Cap&iacute;tulo #1 - One Punch-Man']] lasts = [['https://mangahost.net/manga/one-punch-man/108', 'Cap&iacute;tulo #108 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/107.2', 'Cap&iacute;tulo #107.2 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/107.1', 'Cap&iacute;tulo #107.1 - One Punch-Man']] page = File.open(CHAPTER_PAGE[0]).read stub_request(:get, "https://mangahost.net/manga/one-punch-man"). to_return(status:[200, "OK"], body: page, headers: { "Content-Type" => "text/html; charset=UTF-8"}) result = @site_parser.parse("https://mangahost.net/manga/one-punch-man", DManga::MangaHostParser::CHAPTER_LINK_REGEX[1]) assert_equal firsts, result[-3..-1] assert_equal lasts, result[0..2] end def test_parse_chapters_page_for_short_mangas # test the first threes and last threes firsts = [["Capítulo #21-30 - Capítulos do 21 ao 30!", "http://mangahost.net/manga/tomo-chan-wa-onna-no-ko/21-30"], ["Capítulo #11-20 - Capítulos do 11 ao 20!", "http://mangahost.net/manga/tomo-chan-wa-onna-no-ko/11-20"], ["Capítulo #1-10 - Capítulos do 01 ao 10!", "http://mangahost.net/manga/tomo-chan-wa-onna-no-ko/1-10"]] lasts = [["Capítulo #491-500 - Tomo-chan wa Onna no ko!", "http://mangahost.net/manga/tomo-chan-wa-onna-no-ko/491-500"], ["Capítulo #481-490 - Tomo-chan wa Onna no ko!", "http://mangahost.net/manga/tomo-chan-wa-onna-no-ko/481-490"], ["Capítulo #471-480 - Tomo-chan wa Onna no ko!", "http://mangahost.net/manga/tomo-chan-wa-onna-no-ko/471-480"]] page = File.open(CHAPTER_PAGE[1]).read stub_request(:get, "https://mangahost.net/manga/tomo-chan"). to_return(status:[200, "OK"], body: page, headers: { "Content-Type" => "text/html; charset=UTF-8"}) result = @site_parser.parse("https://mangahost.net/manga/tomo-chan", DManga::MangaHostParser::CHAPTER_LINK_REGEX[0]) assert_equal firsts, result[-3..-1] assert_equal lasts, result[0..2] end def test_parse_imgs_page_alt_regex firsts = ["https:\\/\\/img.mangahost.me\\/br\\/images\\/tokyo-ghoulre\\/99\\/00.jpg.webp", "https:\\/\\/img.mangahost.me\\/br\\/images\\/tokyo-ghoulre\\/99\\/01.png.webp", "https:\\/\\/img.mangahost.me\\/br\\/images\\/tokyo-ghoulre\\/99\\/02.png.webp"] lasts = ["https:\\/\\/img.mangahost.me\\/br\\/images\\/tokyo-ghoulre\\/99\\/16.png.webp", "https:\\/\\/img.mangahost.me\\/br\\/images\\/tokyo-ghoulre\\/99\\/17.png.webp", "https:\\/\\/img.mangahost.me\\/br\\/images\\/tokyo-ghoulre\\/99\\/18.png.webp"] page = File.open(IMGS_PAGE[1]).read stub_request(:get, 'https://mangahost.net/manga/tokyo-ghoulre/99'). to_return(status:[200, "OK"], body: page) result = @site_parser.parse("https://mangahost.net/manga/tokyo-ghoulre/99", DManga::MangaHostParser::IMG_LINK_REGEX[1]) assert_equal firsts, result[0..2] assert_equal lasts, result[-3..-1] end def test_select_manga_when_manga_was_found mangas = [["https://mangahost.net/manga/db-x-saitama-doujinshi", "DB X Saitama (Doujinshi)"], ["https://mangahost.net/manga/fire-punch", "Fire Punch"], ["https://mangahost.net/manga/one-punch-man", "One Punch-Man"], ["https://mangahost.net/manga/one-punch-man-one", "One Punch-Man (One)"], ["https://mangahost.net/manga/punch", "Punch!"], ["https://mangahost.net/manga/short-program-girls-type", "Short Program - Girl's Type"]] $stdin = StringIO.new("2") #simulate user input @site_parser.select_manga(mangas) $stdin = STDIN assert_equal @site_parser.manga_url, mangas[1][0] assert_equal @site_parser.manga_name, mangas[1][1] end # test "test select manga when manga was not found" do def test_select_manga_when_manga_was_not_found mangas = [["https://mangahost.net/manga/db-x-saitama-doujinshi", "DB X Saitama (Doujinshi)"], ["https://mangahost.net/manga/fire-punch", "Fire Punch"], ["https://mangahost.net/manga/one-punch-man-one", "One Punch-Man (One)"], ["https://mangahost.net/manga/punch", "Punch!"]] $stdin = StringIO.new("6") #simulate user input assert_raises(DManga::MangaNotFoundError) {@site_parser.select_manga(mangas)} $stdin = STDIN end def test_select_manga_when_search_returns_no_manga mangas = [] assert_raises(DManga::MangaNotFoundError) {@site_parser.select_manga(mangas)} end def test_select_chapters_with_range chapters = [['https://mangahost.net/manga/one-punch-man/10', 'Cap&iacute;tulo #10 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/9', 'Cap&iacute;tulo #9 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/8', 'Cap&iacute;tulo #8 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/7', 'Cap&iacute;tulo #7 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/6', 'Cap&iacute;tulo #6 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/5', 'Cap&iacute;tulo #5 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/4', 'Cap&iacute;tulo #4 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/3', 'Cap&iacute;tulo #3 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/2', 'Cap&iacute;tulo #2 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/1', 'Cap&iacute;tulo #1 - One Punch-Man']] @site_parser.chapters = chapters $stdin = StringIO.new("1-5\n") @site_parser.select_chapters $stdin = STDIN assert_equal @site_parser.chapters, chapters[-5..-1] end def test_select_chapters_with_specific_number chapters = [['https://mangahost.net/manga/one-punch-man/10', 'Cap&iacute;tulo #10 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/9', 'Cap&iacute;tulo #9 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/8', 'Cap&iacute;tulo #8 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/7', 'Cap&iacute;tulo #7 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/6', 'Cap&iacute;tulo #6 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/5', 'Cap&iacute;tulo #5 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/4', 'Cap&iacute;tulo #4 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/3', 'Cap&iacute;tulo #3 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/2', 'Cap&iacute;tulo #2 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/1', 'Cap&iacute;tulo #1 - One Punch-Man']] @site_parser.chapters = chapters $stdin = StringIO.new("1,3,4\n") @site_parser.select_chapters $stdin = STDIN assert_equal(@site_parser.chapters, [chapters[4 * -1], chapters[3 * -1], chapters[1 * -1]]) end def test_select_all_chapters chapters = [['https://mangahost.net/manga/one-punch-man/10', 'Cap&iacute;tulo #10 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/9', 'Cap&iacute;tulo #9 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/8', 'Cap&iacute;tulo #8 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/7', 'Cap&iacute;tulo #7 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/6', 'Cap&iacute;tulo #6 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/5', 'Cap&iacute;tulo #5 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/4', 'Cap&iacute;tulo #4 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/3', 'Cap&iacute;tulo #3 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/2', 'Cap&iacute;tulo #2 - One Punch-Man'], ['https://mangahost.net/manga/one-punch-man/1', 'Cap&iacute;tulo #1 - One Punch-Man']] @site_parser.chapters = chapters $stdin = StringIO.new("todos\n") @site_parser.select_chapters $stdin = STDIN assert_equal @site_parser.chapters, chapters end def test_create_dir dir_name = "test_dir" @site_parser.create_dir dir_name dir_path = [@site_parser.download_dir, dir_name].join(File::SEPARATOR) assert File.exist? dir_path Dir.rmdir dir_path end def test_remove_invlid_simbols invalid_names = ["Tokyo Ghoul:Re", "Tokyo Ghoul\\Re", "Tokyo Ghoul/Re", "Tokyo Ghoul*Re", "should\\remove/any:invalid*character?in<that>string|end"] corrected_names = ["Tokyo Ghoul_Re", "Tokyo Ghoul_Re", "Tokyo Ghoul_Re", "Tokyo Ghoul_Re", "should_remove_any_invalid_character_in_that_string_end"] invalid_names.each{ |n| @site_parser.remove_invalid_simbols(n) } assert_equal corrected_names, invalid_names end def test_remove_dot_from_folder_name # remove dots if they are in the end or in the start of the name invalid_names = ['narimashita......', 'lllllll...', '...mmmmm', '...........jjjjjjjjjj'] corrected_names = ['narimashita_', 'lllllll_', '_mmmmm', '_jjjjjjjjjj'] invalid_names.each{ |n| @site_parser.remove_invalid_simbols(n) } assert_equal corrected_names, invalid_names # don't remove dots that are in the middle of the name valid_names = ['name.of.manga', 'name...........manga'] expect_result = ['name.of.manga', 'name...........manga'] valid_names.each { |n| @site_parser.remove_invalid_simbols(n) } assert_equal expect_result, valid_names end def test_imgs_download_normal_uri test_uri = "https://img.mangahost.me/br/mangas_files/shokugeki-no-souma/1/r002.jpg" stub_request(:get, test_uri). to_return(status:[200, "OK"], body: "stub for images file") chp_path = "" original_img_name = "r002.jpg" @site_parser.imgs_download(chp_path, [test_uri]) img_path = [@site_parser.download_dir, original_img_name].join(File::SEPARATOR) assert(File.exist?(img_path), "File r002.jpg should exist") File.delete img_path end def test_imgs_download_with_uri_that_contains_white_space stub_request(:get, "https://img.mangahost.me/br/mangas_files/elfen-lied/1" + "/%5BChrono%5D%20Elfen%20Lied%20-%20Volume%2001%20-%20Capitulo%" + "20001/EL-v01-ch01-001.jpg"). to_return(status:[200, "OK"], body: "stub for images file") chp_path = "" img_uri = ["https://img.mangahost.me/br/mangas_files/elfen-lied/" + "1/[Chrono] Elfen Lied - Volume 01 - Capitulo 001/EL-v01-ch01-001.jpg"] original_img_name = "EL-v01-ch01-001.jpg" @site_parser.imgs_download(chp_path, img_uri) img_path = [@site_parser.download_dir, original_img_name].join(File::SEPARATOR) assert(File.exist?(img_path), "File EL-v01-ch01-001.jpg should exist") File.delete img_path end def test_imgs_download_with_uri_that_contains_utf8_chars test_uri = "https://img.mangahost.me/br/mangas_files/shokugeki-no-souma/1/Créditos.jpg" stub_request(:get, test_uri). to_return(status:[200, "OK"], body: "stub for images file") chp_path = "" original_img_name = "Créditos.jpg" @site_parser.imgs_download(chp_path, [test_uri]) img_path = [@site_parser.download_dir, original_img_name].join(File::SEPARATOR) assert(File.exist?(img_path), "File Créditos.jpg should exist") File.delete img_path end end
ruby
MIT
e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8
2026-01-04T17:58:07.727342Z
false
dkeas/DManga
https://github.com/dkeas/DManga/blob/e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8/lib/dmanga.rb
lib/dmanga.rb
require "dmanga/version" require 'dmanga/util' require 'dmanga/site_parser_base' require 'dmanga/mangahost_parser' require 'dmanga/options' require 'dmanga/zip_file_generator'
ruby
MIT
e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8
2026-01-04T17:58:07.727342Z
false
dkeas/DManga
https://github.com/dkeas/DManga/blob/e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8/lib/dmanga/version.rb
lib/dmanga/version.rb
module DManga VERSION = '1.2.2' end
ruby
MIT
e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8
2026-01-04T17:58:07.727342Z
false
dkeas/DManga
https://github.com/dkeas/DManga/blob/e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8/lib/dmanga/options.rb
lib/dmanga/options.rb
require 'optparse' require 'dmanga/version' module DManga class Options DEFAULT_DOWNLOAD_DIR = "#{ENV['HOME']}/Downloads" attr_reader :download_dir, :verbose, :manga attr_accessor :site def initialize(argv) @download_dir = DEFAULT_DOWNLOAD_DIR @verbose = false @site = "mangahost.cc" parse(argv) @manga = argv[0] end def parse(argv) OptionParser.new do |opts| opts.banner = "Uso: dmanga [opção] <nome do manga>" opts.separator "" opts.separator "Opções:" opts.on('--version', 'Exibe o numero de versão do programa.') do puts "version #{DManga::VERSION}" exit end opts.on('-v', '--verbose', 'Exibe informações da execução do programa.') do @verbose = true end opts.on('-d', '--directory DIRETORIO', 'O diretorio de destino do download. Padrão é Downloads.') do |path| @download_dir = path end opts.on('-h', '--help', 'Exibe esta tela.') do puts opts exit end argv = ['-h'] if argv.empty? opts.parse!(argv) end end end end
ruby
MIT
e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8
2026-01-04T17:58:07.727342Z
false
dkeas/DManga
https://github.com/dkeas/DManga/blob/e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8/lib/dmanga/mangahost_parser.rb
lib/dmanga/mangahost_parser.rb
require 'dmanga/site_parser_base' require 'dmanga/zip_file_generator' module DManga class MangaHostParser < SiteParserBase # url used to search in the site SEARCH_URL = "https://mangahosted.com/find/" # regex to extract url of found mangas SEARCH_LINK_REGEX = /entry-title">\s*<a\s*href="(.*)?"\s*title="(.*)"/ # Regex to extract chapters' url from manga page. # Manga host has two diferent manga pages. # One to medium/short mangas and one to big mangas CHAPTER_LINK_REGEX = [ /capitulo.*?Ler\s+Online\s+-\s+(.*?)['"]\s+href=['"](.*?)['"]/, # for short/medium mangas /<a\s+href=['"](.*?)['"]\s+title=['"]Ler\s+Online\s+-\s+(.*?)\s+\[\]/ # for big mangas ] # regex to extract images' url from chapter page IMG_LINK_REGEX = [/img_\d+['"]\s+src=['"](.*?)['"]/, /url['"]:['"](.*?)['"]\}/] def download @options.site = SEARCH_URL.match(%r{.*://(.*)/find/})[1] # white space is not allowed in the search url. guess_manga_name = @options.manga.gsub(/\s/, '+') # Replace ' ' by '+' guess_manga_name = encode_manga_name(guess_manga_name) search("#{SEARCH_URL}#{guess_manga_name}", SEARCH_LINK_REGEX) # Due the organazation of the chapters page the chapters are # extracted in reverse order @chapters = parse(@manga_url, CHAPTER_LINK_REGEX[0]) do |resul, page| # use long mangas regex if short mangas regex # returns empty array if resul.empty? # Extract chapters name and url and # swap chapter[0](name) with chapter[1](url) # to conform with result from CHAPTER_LINK_REGEX[0] page.scan(CHAPTER_LINK_REGEX[1]) {|chapter| resul << chapter.rotate} end resul end # correct utf-8 errors correct_chapters_name # prompt user to select chapters to download select_chapters # remove simbols that cannot be used in folder's name on windows remove_invalid_simbols(@manga_name) # create manga directory remove_invalid_simbols(@manga_name) create_dir(@manga_name) # download selected chapters @chapters.reverse_each do |chapter| imgs_url = parse(chapter[1], IMG_LINK_REGEX[0]) do |resul, page| # use second pattern if the first returns a empty # array if resul.empty? page.scan(IMG_LINK_REGEX[1]) do |img| resul << img[0] end end resul.each do |img| # some images urls are incorrect and need to be corrected. For exemple: # img.mangahost.net/br/images/img.png.webp => img.mangahost.net/br/mangas_files/img.png img.sub!(/images/, "mangas_files") img.sub!(/\.webp/, "") #correct créditos img problem correct_image_uri(img) img.gsub!(%r{\\}, "") end resul end # create chapter directory relative to manga directory chapter_name = "#{chapter[0]}" # remove simbols that cannot be used in folder's name on windows remove_invalid_simbols chapter_name chapter_dir = "#{@manga_name}/#{chapter_name}" create_dir(chapter_dir) DManga::display_feedback "\nBaixando #{chapter_name}" imgs_download(chapter_dir, imgs_url) end end private # Due to problems with open-uri and unicode # some chapters' name need to be corrected. # substitute Cap$amptulo for capitulo. def correct_chapters_name @chapters.each {|chapter| chapter[0].sub!(/[cC]ap.*?tulo/, "capitulo")} end UNICODE_TABLE = { "\\u00e1" => "\u00e1", "\\u00e9" => "\u00e9", "\\u00ed" => "\u00ed" } # this will allow utf-8 characters in manga name # e.g. japanese names def encode_manga_name(manga_name) Addressable::URI.encode(manga_name) end # Due to problems with open-uri and utf-8 # some images uris need to be corrected. # substitute Cru00e9ditos for Créditos. # one url at a time def correct_image_uri(img_uri) result = img_uri.scan(/\\u..../i) result.each do |r| img_uri.sub!(r, UNICODE_TABLE[r.downcase]) end end end end
ruby
MIT
e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8
2026-01-04T17:58:07.727342Z
false
dkeas/DManga
https://github.com/dkeas/DManga/blob/e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8/lib/dmanga/os.rb
lib/dmanga/os.rb
# module to set operating system module DManga module OS def self.windows? /cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM end end end
ruby
MIT
e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8
2026-01-04T17:58:07.727342Z
false
dkeas/DManga
https://github.com/dkeas/DManga/blob/e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8/lib/dmanga/zip_file_generator.rb
lib/dmanga/zip_file_generator.rb
require 'zip' # This is a simple example which uses rubyzip to # recursively generate a zip file from the contents of # a specified directory. The directory itself is not # included in the archive, rather just its contents. # # Usage: # directory_to_zip = "/tmp/input" # output_file = "/tmp/out.zip" # zf = ZipFileGenerator.new(directory_to_zip, output_file) # zf.write() module DManga class ZipFileGenerator def initialize(input_dir, output_file) @input_dir = input_dir @output_file = output_file end # zip the input directory def write entries = Dir.entries(@input_dir) - %w(. ..) ::Zip::File.open(@output_file, ::Zip::File::CREATE) do |io| write_entries entries, '', io end end private # a helper method to make the recursion work: def write_entries(entries, path, io) entries.each do |e| zip_file_path = path == '' ? e : File.join(path, e) disk_file_path = File.join(@input_dir, zip_file_path) puts "Deflating #{disk_file_path}" put_into_archive(disk_file_path, io, zip_file_path) end end def put_into_archive(disk_file_path, io, zip_file_path) io.get_output_stream(zip_file_path) do |f| f.write(File.open(disk_file_path, 'rb').read) end end end end
ruby
MIT
e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8
2026-01-04T17:58:07.727342Z
false
dkeas/DManga
https://github.com/dkeas/DManga/blob/e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8/lib/dmanga/site_parser_base.rb
lib/dmanga/site_parser_base.rb
require 'dmanga/options' require 'dmanga/os' require 'ruby-progressbar' require 'open-uri' require 'addressable/uri' # todo: if downloading returns an error, skip to next chapter module DManga class SiteParserBase USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0" attr_accessor :manga_name, :manga_url, :chapters, :verbose def initialize(argv) @options = Options.new(argv) @manga_url = nil # manga_name is also used as manga directory name @manga_name = nil @chapters = nil end # Parse the html and extract links that match the pattern. # Can receive a block. def parse(url, regex) DManga::display_feedback "\nfetching #{url}" if @options.verbose result = [] URI.open(url, "User-Agent" => USER_AGENT) do |response| if response.status[1] == "OK" DManga::display_feedback "parsing #{url}" if @options.verbose page = response.read page.scan(regex) do |r| # => try first regex if r.length < 2 result << r[0] else result << r end end result = yield(result, page) if block_given? else DManga::display_error("ERRO: Servidor respondeu: #{response.status.inpect}") end end result end def search(url, regex) DManga::display_feedback "Iniciando busca em #{@options.site}" search_result = parse(url, regex) select_manga(search_result) end def select_manga(mangas) puts # just a new line for better output unless mangas.empty? mangas.each_with_index do |manga, index| DManga::display_feedback "(#{index + 1}) #{manga[1]}" end DManga::display_prompt "Selecionar manga: " res = $stdin.gets.chomp if res =~ /^\d+$/ res = res.to_i if res > 0 && res <= mangas.length @manga_name = mangas[res - 1][1] @manga_url = mangas[res - 1][0] else DManga::display_warn("ERRO: Opção inválida") end else DManga::display_warn("ERRO: Opção inválida") end else raise MangaNotFoundError, "manga não encontrado" end raise MangaNotFoundError, "manga não encontrado" if @manga_url.nil? end def select_chapters DManga::display_feedback "\nCapítulos:" @chapters.reverse_each.with_index do |chapter, index| DManga::display_feedback "(#{index + 1})\t#{chapter[0]}" end answer = nil DManga::display_feedback "\n#{@chapters.length} capitulos encontrados\n" loop do DManga::display_prompt("Quais capitulos você quer baixar? ") answer = $stdin.gets.chomp if answer == "o" || answer.empty? DManga::display_feedback( <<-EOS o - exibe opções. c - cancelar. todos - baixar todos os capítulos. inicio-fim - baixar intervalo selecionado. Ex: 0-10 - baixa do 0 ao 10. capNum,capNum,capNum - baixar capitulos selecionados. Ex: 29,499,1 - baixa capitulos 29, 499 e 1. EOS ) elsif answer == "c" DManga::display_feedback("Saindo") exit true elsif answer == "todos" DManga::display_feedback "Baixando todos os capítulos" if @options.verbose break elsif answer =~ /(\d+)-(\d+)/ b = Integer($2) <= @chapters.length ? Integer($2) * -1 : @chapters.length * -1 e = Integer($1) * -1 @chapters = @chapters[b..e] DManga::display_feedback "Baixando capítulos do #{$1} ao #{$2}" if @options.verbose break elsif answer =~ /^(\d+,?)+$/ answer = answer.split(',') aux = [] # downloads are processed in reverse order (to make # it in crescent order)so the answer is reversed too answer.reverse_each do |c| chp = @chapters[Integer(c) * -1] aux << chp unless chp.nil? end @chapters = aux DManga::display_feedback "Baixando capítulos #{answer.to_s}" if @options.verbose break else DManga::display_warn("\tOpção invalida") end end end # return a progressbar suitable to the user operating system def get_progressbar if DManga::OS.windows? return ProgressBar.create(:title => 'Baixando', :starting_at => 20, :length => 70, :total => nil) else return ProgressBar.create(:title => 'Baixando', :starting_at => 20, :total => nil) end end # download images to path relative to Downloads directory def imgs_download(chp_path, imgs_urls) imgs_urls.each do |url| original_filename = url.slice(/(?u)(\w|[_-])+\.(png|jpg)/i) img_path = [@options.download_dir, chp_path, original_filename].join(File::SEPARATOR) unless File.exist? img_path encoded_url = Addressable::URI.encode(url) DManga::display_feedback "\n#{encoded_url}" pbar = get_progressbar URI.open( encoded_url, "User-Agent" => USER_AGENT, :progress_proc => lambda {|s| pbar.increment } ) do |response| if response.status[1] == "OK" DManga::display_feedback "Salvando imagem em:'#{img_path}'" if @options.verbose File.open(img_path, "wb") do |img| img.puts response.read end else puts "Error #{reponse.status}" end end puts end end end # check if the directory exists and # create a directory relative to downlaod directory def create_dir(relative_path) absolute_path = [@options.download_dir, relative_path].join(File::SEPARATOR) DManga::display_feedback "\nCriando diretorio '#{relative_path}' em '#{@options.download_dir}'" if @options.verbose unless Dir.exist? absolute_path Dir.mkdir(absolute_path) puts if @options.verbose ## just a blank line for prettier output else DManga::display_feedback "'#{relative_path}' directorio ja existe" if @options.verbose end end #def zip_chapter ## TODO #end # Returns the download destination directory def download_dir @options.download_dir end def remove_invalid_simbols(name) # windows OS dont accept these simbols in folder name name.gsub!(%r{[/\\:*?"<>|]|(\.+$)|(^\.+)}, '_') end end end
ruby
MIT
e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8
2026-01-04T17:58:07.727342Z
false
dkeas/DManga
https://github.com/dkeas/DManga/blob/e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8/lib/dmanga/util.rb
lib/dmanga/util.rb
require 'formatador' module DManga class MangaNotFoundError < RuntimeError end def self.display_error(message, error) Formatador.display_line("\t[_red_][white][bold]ERRO: #{message}.[/]") Formatador.display_line("\t[_red_][white][bold]ERROR: #{error.message}.[/]") end def self.display_feedback(str) Formatador.display_line("[magenta][bold]#{str}[/]") end def self.display_prompt(str) Formatador.display("[white][bold]#{str}[/]") end def self.display_warn(str) Formatador.display_line("[red][bold]#{str}[/]") end end
ruby
MIT
e8b94508c8fdf169f3e00cb2bdfe695c19e5beb8
2026-01-04T17:58:07.727342Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/spec_helper.rb
spec/spec_helper.rb
require 'coveralls' Coveralls.wear! SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new([ Coveralls::SimpleCov::Formatter, SimpleCov::Formatter::HTMLFormatter ]) ENV["RAILS_ENV"] = "test" require File.expand_path("../dummy/config/environment.rb", __FILE__) require 'pry' Rails.backtrace_cleaner.remove_silencers! require 'rspec/rails' require 'capybara/rspec' Dir[Rails.root.join("../../spec/support/**/*.rb")].each {|f| require f} RSpec.configure do |config| config.infer_spec_type_from_file_location! config.order = "random" config.filter_run_excluding performance: true end load File.expand_path("../dummy/db/schema.rb", __FILE__)
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/support/database_cleaner.rb
spec/support/database_cleaner.rb
require 'database_cleaner' RSpec.configure do |config| config.before(:suite) do DatabaseCleaner.clean_with(:truncation) end config.before(:each) do DatabaseCleaner.strategy = :transaction end config.before(:each, :js => true) do DatabaseCleaner.strategy = :truncation end config.before(:each) do DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean end end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/performance/slow_filterer_spec.rb
spec/performance/slow_filterer_spec.rb
require 'spec_helper' require 'benchmark/ips' describe 'Performance of SlowFilterer', performance: true do it 'performs fast' do Benchmark.ips do |x| params = { name: 'one', a: 'two', b: 'three', sort: 'field_21' } # Add a bunch of useless params, too (0..100).each do |x| params[x.to_s] = 'whatever' end x.report('filterer instantiation') do SlowFilterer.filter(params).to_a end end end end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/features/basic_spec.rb
spec/features/basic_spec.rb
require 'spec_helper' module BasicSpecHelper if defined?(Kaminari) def ensure_page_links(*args) expect(page).to have_selector('nav.pagination') args.each do |x| if x.is_a?(Integer) expect(page).to have_link(x) else expect(page).to have_selector('li', text: x) end end end def have_current_page(page) have_selector 'span.current', text: page end else def ensure_page_links(*args) expect(page).to have_selector('div.pagination') args.each do |x| if x.is_a?(Integer) expect(page).to have_link(x) else expect(page).to have_selector('li', text: x) end end end def have_current_page(page) have_selector 'em.current', text: page end end end include BasicSpecHelper describe 'Filterer', :type => :feature do subject { page } describe 'pagination' do before do 300.times { Person.create(name: 'Foo bar', email: 'foo@bar.com') } end it 'renders the pagination correctly' do visit people_path expect(page).to have_selector 'div.person', count: 10 ensure_page_links(2, 3, 4, 5) expect(page).to have_current_page('1') end it 'properly links between pages' do visit people_path click_link '2' expect(page).to have_selector 'div.person', count: 10 ensure_page_links(1, 3, 4, 5, 6) expect(page).to have_current_page('2') end it 'can be configured to skip pagination entirely' do visit no_pagination_people_path expect(page).to have_selector 'div.person', count: 300 end end describe 'filtering' do before do 5.times { Person.create(name: 'Foo bar', email: 'foo@bar.com') } Person.create(name: 'Adam') end it 'displays all people' do visit people_path expect(page).to have_selector('.person', count: 6) end it 'properly filters the results' do visit people_path(name: 'Adam') expect(page).to have_selector('.person', count: 1) end end describe 'sorting' do let!(:bill) { Person.create(name: 'Bill', email: 'foo@bar.com') } let!(:adam) { Person.create(name: 'Adam', email: 'foo@bar.com') } it 'sorts properly' do visit people_path expect(find('.person:eq(1)')).to have_text 'Adam' expect(find('.person:eq(2)')).to have_text 'Bill' end it 'reverses sort' do visit people_path(direction: 'desc') expect(find('.person:eq(1)')).to have_text 'Bill' expect(find('.person:eq(2)')).to have_text 'Adam' end it 'changes sort option' do visit people_path(sort: 'id') expect(find('.person:eq(1)')).to have_text 'Bill' expect(find('.person:eq(2)')).to have_text 'Adam' visit people_path(sort: 'id', direction: 'desc') expect(find('.person:eq(1)')).to have_text 'Adam' expect(find('.person:eq(2)')).to have_text 'Bill' end end end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/app/filterers/slow_filterer.rb
spec/dummy/app/filterers/slow_filterer.rb
class SlowFilterer < Filterer::Base sort_option 'name', default: true, tiebreaker: true def starting_query Person end def param_name(x) results.where(name: x) end def param_a(x) results end def param_b(x) results end def param_c(x) results end def param_d(x) results end def param_e(x) results end end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/app/filterers/person_filterer.rb
spec/dummy/app/filterers/person_filterer.rb
class PersonFilterer < Filterer::Base def starting_query Person end def param_name(x) results.where(name: x) end sort_option 'name', default: true sort_option 'id' self.per_page = 10 end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/app/filterers/unpaginated_person_filterer.rb
spec/dummy/app/filterers/unpaginated_person_filterer.rb
class UnpaginatedPersonFilterer < PersonFilterer self.per_page = nil end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/app/helpers/application_helper.rb
spec/dummy/app/helpers/application_helper.rb
module ApplicationHelper end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/app/controllers/people_controller.rb
spec/dummy/app/controllers/people_controller.rb
class PeopleController < ApplicationController def index @people = PersonFilterer.filter(params) end def no_pagination @people = UnpaginatedPersonFilterer.filter(params) render :index end end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/app/controllers/application_controller.rb
spec/dummy/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/app/models/person.rb
spec/dummy/app/models/person.rb
class Person < ActiveRecord::Base belongs_to :company end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/app/models/company.rb
spec/dummy/app/models/company.rb
class Company < ActiveRecord::Base has_many :people end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/db/schema.rb
spec/dummy/db/schema.rb
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20131117183023) do create_table "companies", force: true do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" end create_table "people", force: true do |t| t.string "name" t.string "email" t.integer "company_id" t.datetime "created_at" t.datetime "updated_at" end end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/db/migrate/20131117183023_create_dummy_database.rb
spec/dummy/db/migrate/20131117183023_create_dummy_database.rb
class CreateDummyDatabase < ActiveRecord::Migration def change create_table :people do |t| t.string :name t.string :email t.integer :company_id t.timestamps end create_table :companies do |t| t.string :name t.timestamps end end end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/config/application.rb
spec/dummy/config/application.rb
require File.expand_path('../boot', __FILE__) require 'rails/all' Bundler.require(*Rails.groups) require 'filterer' module Dummy class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de end end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/config/environment.rb
spec/dummy/config/environment.rb
# Load the Rails application. require File.expand_path('../application', __FILE__) if ENV['WILL_PAGINATE'] require 'will_paginate' else require 'kaminari' end # Initialize the Rails application. Dummy::Application.initialize!
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/config/routes.rb
spec/dummy/config/routes.rb
Rails.application.routes.draw do resources :people do collection do get 'no_pagination' end end end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/config/boot.rb
spec/dummy/config/boot.rb
# Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__) require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE']) $LOAD_PATH.unshift File.expand_path('../../../../lib', __FILE__)
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/config/initializers/filter_parameter_logging.rb
spec/dummy/config/initializers/filter_parameter_logging.rb
# Be sure to restart your server when you modify this file. # Configure sensitive parameters which will be filtered from the log file. Rails.application.config.filter_parameters += [:password]
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/config/initializers/session_store.rb
spec/dummy/config/initializers/session_store.rb
# Be sure to restart your server when you modify this file. Dummy::Application.config.session_store :cookie_store, key: '_dummy_session'
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/config/initializers/wrap_parameters.rb
spec/dummy/config/initializers/wrap_parameters.rb
# Be sure to restart your server when you modify this file. # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:json] if respond_to?(:wrap_parameters) end # To enable root element in JSON for ActiveRecord objects. # ActiveSupport.on_load(:active_record) do # self.include_root_in_json = true # end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/config/initializers/inflections.rb
spec/dummy/config/initializers/inflections.rb
# Be sure to restart your server when you modify this file. # Add new inflection rules using the following format. Inflections # are locale specific, and you may define rules for as many different # locales as you wish. All of these examples are active by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', 'people' # inflect.uncountable %w( fish sheep ) # end # These inflection rules are supported but not enabled by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.acronym 'RESTful' # end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/config/initializers/backtrace_silencers.rb
spec/dummy/config/initializers/backtrace_silencers.rb
# Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. # Rails.backtrace_cleaner.remove_silencers!
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/config/initializers/mime_types.rb
spec/dummy/config/initializers/mime_types.rb
# Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf # Mime::Type.register_alias "text/html", :iphone
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/config/initializers/secret_token.rb
spec/dummy/config/initializers/secret_token.rb
# Be sure to restart your server when you modify this file. # Your secret key is used for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. # You can use `rake secret` to generate a secure secret key. # Make sure your secret_key_base is kept private # if you're sharing your code publicly. Dummy::Application.config.secret_key_base = 'dcf4f83546f3f99b9aa881c3f7d78085a17b3e79155515da37ecd2b5265b2a7ceb3208a82fb9d7cf2feb494d89010baf8b67db330b6213d9c45c1124920194df'
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/config/environments/test.rb
spec/dummy/config/environments/test.rb
Dummy::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Do not eager load code on boot. This avoids loading your whole application # just for the purpose of running a single test. If you are using a tool that # preloads Rails for running tests, you may have to set it to true. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates. config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/config/environments/development.rb
spec/dummy/config/environments/development.rb
Dummy::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/dummy/config/environments/production.rb
spec/dummy/config/environments/production.rb
Dummy::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both thread web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Enable Rack::Cache to put a simple HTTP cache in front of your application # Add `rack-cache` to your Gemfile before enabling this. # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid. # config.action_dispatch.rack_cache = true # Disable Rails's static asset server (Apache or nginx will already do this). config.serve_static_assets = false # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Generate digests for assets URLs. config.assets.digest = true # Version of your assets, change this if you want to expire all your assets. config.assets.version = '1.0' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Set to :debug to see everything in the log. config.log_level = :info # Prepend all log lines with the following tags. # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups. # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production. # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = "http://assets.example.com" # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. # config.assets.precompile += %w( search.js ) # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Disable automatic flushing of the log to improve performance. # config.autoflush_log = false # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/lib/filterer/active_record_spec.rb
spec/lib/filterer/active_record_spec.rb
require 'spec_helper' describe 'ActiveRecord' do it 'finds for a model' do included = Person.create(name: 'b') excluded = Person.create(name: 'c') params = { name: 'b' } expect(PersonFilterer).to receive(:new).with(params, anything).and_call_original expect(Person.filter(params)).to eq [included] end it 'preserves an existing query' do person = Person.create(name: 'b') expect(Person.where(name: 'b').filter).to eq [person] expect(Person.where(name: 'asdf').filter).to eq [] end it 'finds for a model' do expect(PersonFilterer).to receive(:new).with({}, anything).and_call_original Company.filter({}, filterer_class: 'PersonFilterer') end it 'finds for a relation' do company = Company.create(name: 'foo') included = Person.create(company: company) excluded = Person.create expect(Company.first.people.filter).to eq [included] end it 'throws the correct error when not found' do expect do Company.all.filter({}) end.to raise_error(/CompanyFilterer/) end end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/spec/lib/filterer/base_spec.rb
spec/lib/filterer/base_spec.rb
require 'spec_helper' class FakeQuery COUNT = 5 def method_missing(method, *args) self end def to_str 'FakeQuery' end def to_ary ['FakeQuery'] end def count(*args); COUNT end; end class DefaultFilterer < Filterer::Base; end; class MutationFilterer < Filterer::Base def starting_query # This would really be doing it wrong... params[:foo] = 'bar' FakeQuery.new end end class DefaultParamsFilterer < Filterer::Base def starting_query FakeQuery.new end def defaults { foo: 'bar' } end end class DefaultFiltersFilterer < Filterer::Base def starting_query FakeQuery.new end def apply_default_filters if opts[:foo] results.where(foo: 'bar') end end end class ReturnNilFilterer < Filterer::Base def starting_query Person.all end def param_foo(x) # nil end end class UnscopedFilterer < Filterer::Base def starting_query Person.select('name, email') end end class SmokeTestFilterer < Filterer::Base def starting_query FakeQuery.new end end class SortingFiltererA < Filterer::Base def starting_query FakeQuery.new end sort_option 'id', default: true end class InheritedSortingFiltererA < SortingFiltererA end class SortingFiltererB < Filterer::Base def starting_query FakeQuery.new end sort_option 'id', default: true sort_option 'thetiebreaker', tiebreaker: true end class SortingFiltererC < Filterer::Base def starting_query FakeQuery.new end sort_option 'id', default: true sort_option Regexp.new('foo([0-9]+)'), -> (matches) { matches[1] } end class SortingFiltererD < Filterer::Base def starting_query FakeQuery.new end sort_option 'foo', 'baz', nulls_last: true end class SortingFiltererE < Filterer::Base def starting_query FakeQuery.new end def something_important 'yeehaw' end sort_option 'id', default: true sort_option Regexp.new('foo([0-9]+)'), -> (matches) { matches[1] } sort_option Regexp.new('zoo([0-9]+)'), -> (matches) { if matches[1].to_i > 10 'zoo' end } sort_option 'context', -> (_matches) { something_important } end class SortingFiltererF < SortingFiltererE sort_option 'tiebreak', tiebreaker: true end class PaginationFilterer < Filterer::Base def starting_query FakeQuery.new end end class PaginationFiltererB < PaginationFilterer self.per_page = 30 end class PaginationFiltererWithOverride < PaginationFilterer self.per_page = 20 self.allow_per_page_override = true end class PaginationFiltererInherit < PaginationFiltererB end describe Filterer::Base do it 'warns if starting_query is not overriden' do expect { DefaultFilterer.new }.to raise_error('You must override this method!') end it 'allows start query in the opts hash' do expect { DefaultFilterer.new({}, starting_query: Person.select('name, email')) }.to_not raise_error end it 'does not mutate the params hash' do params = {} filterer = MutationFilterer.new(params) expect(params).to eq({}) end it 'adds default params' do filterer = DefaultParamsFilterer.new({}) expect(filterer.params).to eq('foo' => 'bar') end it 'applies default filters' do expect_any_instance_of(FakeQuery).to receive(:where).with(foo: 'bar').and_return(FakeQuery.new) filterer = DefaultFiltersFilterer.filter({}, foo: 'bar') end it 'allows returning nil from default filters' do expect_any_instance_of(FakeQuery).to receive(:where).with(bar: 'baz').and_return(FakeQuery.new) filterer = DefaultFiltersFilterer.filter({}).where(bar: 'baz') end it 'passes parameters to the correct methods' do expect_any_instance_of(SmokeTestFilterer).to receive(:param_foo).with('bar').and_return(FakeQuery.new) SmokeTestFilterer.filter(foo: 'bar') end it 'does not pass blank parameters' do expect_any_instance_of(SmokeTestFilterer).not_to receive(:param_foo) SmokeTestFilterer.new(foo: '') end it 'allows returning nil from a param_* method' do expect(ReturnNilFilterer.filter(foo: 'bar')).to eq([]) end describe 'sorting' do it 'orders by ID by default' do allow_any_instance_of(FakeQuery).to( receive_message_chain(:model, :table_name). and_return('asdf') ) expect_any_instance_of(FakeQuery).to receive(:order). with('asdf.id asc'). and_return(FakeQuery.new) filterer = SmokeTestFilterer.new expect(filterer.sort).to eq 'default' end it 'applies a default sort' do expect_any_instance_of(FakeQuery).to receive(:order).with('id asc').and_return(FakeQuery.new) filterer = SortingFiltererA.new expect(filterer.sort).to eq 'id' end it 'applies a default sort when inheriting a class' do expect_any_instance_of(FakeQuery).to receive(:order).with('id asc').and_return(FakeQuery.new) filterer = InheritedSortingFiltererA.new expect(filterer.sort).to eq 'id' end it 'can include a tiebreaker' do expect_any_instance_of(FakeQuery).to receive(:order).with('id asc , thetiebreaker').and_return(FakeQuery.new) filterer = SortingFiltererB.new end it 'can match by regexp' do expect_any_instance_of(FakeQuery).to receive(:order).with('111 asc').and_return(FakeQuery.new) filterer = SortingFiltererC.new(sort: 'foo111') expect(filterer.sort).to eq 'foo111' end it 'does not choke on a nil param' do expect_any_instance_of(FakeQuery).to receive(:order).with('id asc').and_return(FakeQuery.new) filterer = SortingFiltererC.new end it 'can apply a proc' do expect_any_instance_of(FakeQuery).to receive(:order).with('111 asc').and_return(FakeQuery.new) filterer = SortingFiltererC.new(sort: 'foo111') end it 'can put nulls last' do expect_any_instance_of(FakeQuery).to receive(:order).with('baz asc NULLS LAST').and_return(FakeQuery.new) filterer = SortingFiltererD.new(sort: 'foo') end it 'can change to desc' do expect_any_instance_of(FakeQuery).to receive(:order).with('baz desc NULLS LAST').and_return(FakeQuery.new) filterer = SortingFiltererD.new(sort: 'foo', direction: 'desc') end it 'can distinguish between two regexps' do expect_any_instance_of(FakeQuery).to receive(:order).with('zoo asc').and_return(FakeQuery.new) filterer = SortingFiltererE.new(sort: 'zoo111') end it 'still applies the tiebreaker' do expect_any_instance_of(FakeQuery).to receive(:order).with('zoo asc , tiebreak').and_return(FakeQuery.new) filterer = SortingFiltererF.new(sort: 'zoo111') end it 'calls with context' do expect_any_instance_of(FakeQuery).to receive(:order).with('yeehaw asc , tiebreak').and_return(FakeQuery.new) filterer = SortingFiltererF.new(sort: 'context') end it 'applies the default sort if the proc returns nil' do allow_any_instance_of(FakeQuery).to( receive_message_chain(:model, :table_name). and_return('asdf') ) expect_any_instance_of(FakeQuery).to receive(:order).with('asdf.id asc').and_return(FakeQuery.new) filterer = SortingFiltererE.new(sort: 'zoo1') end it 'can distinguish between two regexps part 2' do expect_any_instance_of(FakeQuery).to receive(:order).with('111 asc').and_return(FakeQuery.new) filterer = SortingFiltererE.new(sort: 'foo111') end it 'throws an error when key is a regexp and no query string given' do expect { class ErrorSortingFiltererA < Filterer::Base def starting_query FakeQuery.new end sort_option Regexp.new('hi') end }.to raise_error(/provide a query string or a proc/) end it 'throws an error when key is a regexp and it is the default key' do expect { class ErrorSortingFiltererB < Filterer::Base def starting_query FakeQuery.new end sort_option Regexp.new('hi'), 'afdsfasdf', default: true end }.to raise_error(/Default sort option can't have a Regexp key/) end it 'throws an error when option is a tiebreaker and it has a proc' do expect { class ErrorSortingFiltererC < Filterer::Base def starting_query FakeQuery.new end sort_option 'whoop', -> (matches) { nil }, tiebreaker: true end }.to raise_error(/Tiebreaker can't be a proc/) end end describe 'pagination' do describe 'per_page' do it 'defaults to 20' do filterer = PaginationFilterer.new expect(filterer.send(:per_page)).to eq(20) end it 'can be set to another value' do filterer = PaginationFiltererB.new expect(filterer.send(:per_page)).to eq(30) end it 'inherits when subclassing' do filterer = PaginationFiltererInherit.new expect(filterer.send(:per_page)).to eq(30) end it 'can be overriden' do filterer = PaginationFiltererWithOverride.new expect(filterer.send(:per_page)).to eq(20) filterer = PaginationFiltererWithOverride.new(per_page: '15') expect(filterer.send(:per_page)).to eq(15) end it 'can not be overriden past max' do filterer = PaginationFiltererWithOverride.new(per_page: 100000) expect(filterer.send(:per_page)).to eq(1000) end end end it 'allows accessing the filterer object' do results = UnscopedFilterer.filter expect(results.filterer).to be_a(Filterer::Base) end describe 'unscoping' do it 'unscopes select' do results = UnscopedFilterer.filter if defined?(Kaminari) expect(results.total_count).to eq(0) else expect(results.total_entries).to eq(0) end end end describe 'options' do it 'skips ordering' do expect_any_instance_of(DefaultParamsFilterer).to_not receive(:ordered_results) filterer = DefaultParamsFilterer.filter({}, skip_ordering: true) end it 'skips pagination' do expect_any_instance_of(DefaultParamsFilterer).to_not receive(:paginate_results) filterer = DefaultParamsFilterer.filter({}, skip_pagination: true) end it 'provides a helper method to skip both' do expect_any_instance_of(DefaultParamsFilterer).to_not receive(:ordered_results) expect_any_instance_of(DefaultParamsFilterer).to_not receive(:paginate_results) filterer = DefaultParamsFilterer.chain({}) end it 'provides a helper method to skip pagination' do expect_any_instance_of(DefaultParamsFilterer).to receive(:ordered_results). and_call_original expect_any_instance_of(DefaultParamsFilterer).to_not receive(:paginate_results) filterer = DefaultParamsFilterer.filter_without_pagination({}) end end end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/lib/filterer.rb
lib/filterer.rb
require 'filterer/engine' require 'filterer/base' module Filterer end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/lib/generators/rspec/filterer_generator.rb
lib/generators/rspec/filterer_generator.rb
module Rspec module Generators class FiltererGenerator < Rails::Generators::NamedBase desc "Generate a Filterer spec in spec/filterers/" argument :name, :type => :string, :required => true, :banner => 'FiltererName' source_root File.expand_path("../templates", __FILE__) def copy_files # :nodoc: template "filter_spec.rb", "spec/filterers/#{file_name}_spec.rb" end end end end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/lib/generators/rspec/templates/filter_spec.rb
lib/generators/rspec/templates/filter_spec.rb
require 'spec_helper' describe <%= class_name %> do pending "add some examples to (or delete) #{__FILE__}" end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/lib/generators/test_unit/filterer_generator.rb
lib/generators/test_unit/filterer_generator.rb
module TestUnit module Generators class FiltererGenerator < Rails::Generators::NamedBase desc "Generate a Filterer test in test/filterers/" argument :name, :type => :string, :required => true, :banner => 'FiltererName' source_root File.expand_path("../templates", __FILE__) def copy_files # :nodoc: template "filter_test.rb", "test/filterers/#{file_name}_test.rb" end end end end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/lib/generators/test_unit/templates/filter_test.rb
lib/generators/test_unit/templates/filter_test.rb
require 'test_helper' class <%= class_name %> < ActiveSupport::TestCase # test "the truth" do # assert true # end end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false
dobtco/filterer
https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/lib/generators/filterer/filterer_generator.rb
lib/generators/filterer/filterer_generator.rb
class FiltererGenerator < Rails::Generators::NamedBase desc "Generate a Filterer in app/filterers/" argument :name, :type => :string, :required => true, :banner => 'FiltererName' source_root File.expand_path("../templates", __FILE__) def copy_files # :nodoc: template "filter.rb", "app/filterers/#{file_name}.rb" end hook_for :test_framework end
ruby
MIT
47b16e84651da4769d2932076c087d88fd9de167
2026-01-04T17:58:11.153161Z
false