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 |
|---|---|---|---|---|---|---|---|---|
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown/elements/block_element.rb | lib/minidown/elements/block_element.rb | module Minidown
class BlockElement < Element
BlockTagRegexp = /\A\s*\>\s*/
def parse
unparsed_lines.unshift content
nodes << self
while(child_line = unparsed_lines.shift) do
block = child_line.sub! BlockTagRegexp, ''
doc.parse_line(child_line)
child = nodes.pop
case child
when LineElement
unparsed_lines.unshift child_line
unparsed_lines.unshift nil
when ParagraphElement
child.extra = !!block
nodes << child
else
break if child.nil?
nodes << child
end
end
children_range = (nodes.index(self) + 1)..-1
self.children = nodes[children_range]
nodes[children_range] = []
end
def to_html
build_tag 'blockquote'.freeze do |content|
children.each do |child|
content << child.to_html
end
end
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown/elements/paragraph_element.rb | lib/minidown/elements/paragraph_element.rb | module Minidown
class ParagraphElement < Element
attr_reader :contents
attr_accessor :extra
ExcludeSchemeRegexp = /\A[^@:]+\z/
StringSymbolRegexp = /"|'/
def initialize *_
super
@contents = [raw_content]
@extra = false
end
def parse
if ParagraphElement === nodes.last
nodes.last.contents << raw_content
else
nodes << self
end
end
def text
build_element raw_content
end
def to_html
if @extra
contents.map{|content| ParagraphElement.new(doc, content).to_html }.join ''.freeze
else
contents.map! do |line|
build_element line
end
build_tag 'p'.freeze do |content|
pre_elem = contents.shift
content << pre_elem.to_html
while elem = contents.shift
content << br_tag if TextElement === pre_elem && TextElement === elem
content << elem.to_html
pre_elem = elem
end
end
end
end
private
def build_element content_str
if Utils::Regexp[:raw_html] =~ content_str && (raw = $1) && (ExcludeSchemeRegexp =~ raw || StringSymbolRegexp =~ raw)
RawHtmlElement.new doc, raw
else
TextElement.new doc, content_str
end
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown/elements/text_element.rb | lib/minidown/elements/text_element.rb | module Minidown
class TextElement < Element
EscapeChars = %w{# > * + \- ` _ { } ( ) . ! \[ \] ~}
EscapeRegexp = /(?<!\\)\\([#{EscapeChars.join '|'}|\\])/
Regexp = {
tag: /(\\*)<(.+?)(\\*)>/,
quot: /"/,
link: /(?<!\!)\[(.+?)\]\((.+?)\)/,
link_title: /((?<=").+?(?="))/,
link_url: /(\S+)/,
link_ref: /(?<!\!)\[(.+?)\]\s*\[(.*?)\]/,
image: /\!\[(.+?)\]\((.+?)\)/,
image_ref: /\!\[(.+?)\]\s*\[(.*?)\]/,
star: /((?<!\\)\*{1,2})(.+?)\1/,
underline: /(?<=\A|\s)((?<!\\)\_{1,2})(\S+)\1(?=\z|\s)/,
delete_line: /(?<!\\)~~(?!\s)(.+?)(?<!\s)~~/,
quotlink: /\<(.+?)\>/,
link_scheme: /\A\S+?\:\/\//,
email: /\A[A-Za-z0-9]+@[A-Za-z0-9]+\.[A-Za-z0-9]+/,
auto_email: /(?<!\S)[A-Za-z0-9]+@[A-Za-z0-9]+\.[A-Za-z0-9]+(?!\S)/,
auto_link: /(?<!\S)\w+?\:\/\/.+?(?!\S)/,
inline_code: /(?<!\\)(`+)\s*(.+?)\s*(?<!\\)\1/
}.freeze
attr_accessor :escape, :convert, :sanitize
def initialize *_
super
@escape = true
@sanitize = false
@convert = true
end
def parse
nodes << self
end
def content
str = super
str = convert_str(str) if convert
escape_content! str
escape_str! str
escape_html str if sanitize
str
end
def escape_str! str
str.gsub!(EscapeRegexp, '\\1'.freeze) if escape
end
def escape_html str
str.replace Utils.escape_html(str)
end
def escape_content! str
return str unless @escape
escape_html str
str.gsub! Regexp[:tag] do
left, tag, right = $1, $2, $3
tag.gsub! Regexp[:quot] do
'"'.freeze
end
left = left.size.odd? ? "#{left[0..-2]}<" : "#{left}<" if left
left ||= "<".freeze
right = right.size.odd? ? "#{right[0..-2]}>" : "#{right}>" if right
right ||= ">".freeze
"#{left}#{tag}#{right}"
end
str
end
def convert_str str
#auto link
str.gsub! Regexp[:auto_link] do |origin_str|
build_tag 'a'.freeze, href: origin_str do |a|
a << origin_str
end
end
#auto email
str.gsub! Regexp[:auto_email] do |origin_str|
build_tag 'a'.freeze, href: "mailto:#{origin_str}" do |a|
a << origin_str
end
end
#parse <link>
str.gsub! Regexp[:quotlink] do |origin_str|
link = $1
attr = case link
when Regexp[:link_scheme]
{href: link}
when Regexp[:email]
{href: "mailto:#{link}"}
end
attr ? build_tag('a'.freeze, attr){|a| a << link} : origin_str
end
#parse * _
Regexp.values_at(:star, :underline).each do |regex|
str.gsub! regex do |origin_str|
tag_name = $1.size > 1 ? 'strong'.freeze : 'em'.freeze
build_tag tag_name do |tag|
tag << $2
end
end
end
#parse ~~del~~
str.gsub! Regexp[:delete_line] do |origin_str|
build_tag 'del'.freeze do |tag|
tag << $1
end
end
#convert image reference
str.gsub! Regexp[:image_ref] do |origin_str|
alt = $1
id = ($2 && !$2.empty?) ? $2 : $1
ref = doc.links_ref[id.downcase]
if ref
attr = {src: ref[:url], alt: alt}
attr[:title] = ref[:title] if ref[:title] && !ref[:title].empty?
build_tag 'img'.freeze, attr
else
origin_str
end
end
#convert image syntax
str.gsub! Regexp[:image] do
alt, url = $1, $2
url =~ Regexp[:link_title]
title = $1
url =~ Regexp[:link_url]
url = $1
attr = {src: url, alt: alt}
attr[:title] = title if title
build_tag 'img'.freeze, attr
end
#convert link reference
str.gsub! Regexp[:link_ref] do |origin_str|
text = $1
id = ($2 && !$2.empty?) ? $2 : $1
ref = doc.links_ref[id.downcase]
if ref
attr = {href: ref[:url]}
attr[:title] = ref[:title] if ref[:title] && !ref[:title].empty?
build_tag 'a'.freeze, attr do |a|
a << text
end
else
origin_str
end
end
#convert link syntax
str.gsub! Regexp[:link] do
text, url = $1, $2
url =~ Regexp[:link_title]
title = $1
url =~ Regexp[:link_url]
url = $1
attr = {href: url}
attr[:title] = title if title
build_tag 'a'.freeze, attr do |content|
content << text
end
end
escape_content! str
#inline code
str.gsub! Regexp[:inline_code] do |origin_str|
build_tag 'code'.freeze do |code|
code << escape_html($2)
end
end
escape_str! str
@escape = false
str
end
def paragraph
ParagraphElement.new doc, raw_content
end
def to_html
content
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown/elements/list_element.rb | lib/minidown/elements/list_element.rb | module Minidown
class ListElement < Element
attr_accessor :p_tag_content, :contents, :task_list, :checked
CheckedBox = '<input type="checkbox" class="task-list-item-checkbox" checked="" disabled="">'.freeze
UnCheckedBox = '<input type="checkbox" class="task-list-item-checkbox" disabled="">'.freeze
def initialize *_
super
@p_tag_content = false
@contents = [TextElement.new(doc, content)]
@task_list = false
@checked = false
end
def to_html
@contents.map! do |content|
ParagraphElement === content ? content.text : content
end if @p_tag_content
content = list_content
content = build_tag('p'.freeze){|p| p << content} if @p_tag_content
attr = nil
attr = {class: 'task-list-item'.freeze} if @task_list
build_tag 'li'.freeze, attr do |li|
li << content
end
end
def list_content
content = @contents.map(&:to_html).join(@p_tag_content ? br_tag : "\n".freeze)
if @task_list
content = (@checked ? CheckedBox : UnCheckedBox) + content
end
content
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown/elements/code_block_element.rb | lib/minidown/elements/code_block_element.rb | module Minidown
class CodeBlockElement < Element
def initialize *_
super
@code_block_handler = doc.options[:code_block_handler]
end
def parse
nodes << self
while(line = unparsed_lines.shift) do
case line
when Utils::Regexp[:code_block]
break
else
child = TextElement.new(doc, line)
child.escape = false
child.sanitize = @code_block_handler.nil?
child.convert = false
children << child
end
end
end
def lang
@lang ||= content.empty? ? nil : content
end
def children_html
children.map(&:to_html).join("\n".freeze)
end
def to_html
if @code_block_handler
@code_block_handler.call(lang, children_html).to_s
else
attr = lang ? {class: lang} : nil
build_tag 'pre'.freeze do |pre|
pre << build_tag('code'.freeze, attr){ |code| code << children_html }
end
end
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown/elements/line_element.rb | lib/minidown/elements/line_element.rb | module Minidown
class LineElement < Element
attr_accessor :display
def initialize doc, content=nil
super
@display = true
end
def blank?
true
end
def parse
node = nodes.last
@display = (doc.within_block || TextElement === node)
nodes << self
end
def to_html
if @display
br_tag
else
''
end
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown/elements/order_list_element.rb | lib/minidown/elements/order_list_element.rb | module Minidown
class OrderListElement < ListGroupElement
NestRegexp = /\A(\s*)\d+\.\s+(.+)/
ListRegexp = Minidown::Utils::Regexp[:order_list]
def initialize doc, line, indent_level = 0
super doc, line
@children << ListElement.new(doc, content)
@lists = @children.dup
@indent_level = indent_level
@put_back = []
end
def to_html
build_tag 'ol'.freeze do |content|
children.each { |child| content << child.to_html}
end
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown/elements/unorder_list_element.rb | lib/minidown/elements/unorder_list_element.rb | module Minidown
class UnorderListElement < ListGroupElement
TaskRegexp = /\A\[([ x])\](.+)/
NestRegexp = /\A(\s*)[*\-+]\s+(.+)/
ListRegexp = Minidown::Utils::Regexp[:unorder_list]
def initialize doc, line, indent_level = 0
super doc, line
if content =~ TaskRegexp
@task_ul ||= true
list = ListElement.new(doc, $2)
list.task_list = true
list.checked = ($1 == 'x'.freeze)
else
list = ListElement.new(doc, content)
end
@children << list
@lists = @children.dup
@indent_level = indent_level
@put_back = []
end
def to_html
attr = nil
attr = {class: 'task-list'.freeze} if @task_ul
build_tag 'ul'.freeze, attr do |content|
children.each { |child| content << child.to_html}
end
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
teamcapybara/xpath | https://github.com/teamcapybara/xpath/blob/51839ed643d9f28e3df6913fd8ce63fa9379086c/spec/union_spec.rb | spec/union_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe XPath::Union do
let(:template) { File.read(File.expand_path('fixtures/simple.html', File.dirname(__FILE__))) }
let(:doc) { Nokogiri::HTML(template) }
describe '#expressions' do
it 'should return the expressions' do
@expr1 = XPath.generate { |x| x.descendant(:p) }
@expr2 = XPath.generate { |x| x.descendant(:div) }
@collection = XPath::Union.new(@expr1, @expr2)
expect(@collection.expressions).to eq [@expr1, @expr2]
end
end
describe '#each' do
it 'should iterate through the expressions' do
@expr1 = XPath.generate { |x| x.descendant(:p) }
@expr2 = XPath.generate { |x| x.descendant(:div) }
@collection = XPath::Union.new(@expr1, @expr2)
exprs = @collection.map { |expr| expr }
expect(exprs).to eq [@expr1, @expr2]
end
end
describe '#map' do
it 'should map the expressions' do
@expr1 = XPath.generate { |x| x.descendant(:p) }
@expr2 = XPath.generate { |x| x.descendant(:div) }
@collection = XPath::Union.new(@expr1, @expr2)
expect(@collection.map(&:expression)).to eq %i[descendant descendant]
end
end
describe '#to_xpath' do
it 'should create a valid xpath expression' do
@expr1 = XPath.generate { |x| x.descendant(:p) }
@expr2 = XPath.generate { |x| x.descendant(:div).where(x.attr(:id) == 'foo') }
@collection = XPath::Union.new(@expr1, @expr2)
@results = doc.xpath(@collection.to_xpath)
expect(@results[0][:title]).to eq 'fooDiv'
expect(@results[1].text).to eq 'Blah'
expect(@results[2].text).to eq 'Bax'
end
end
describe '#where and others' do
it 'should be delegated to the individual expressions' do
@expr1 = XPath.generate { |x| x.descendant(:p) }
@expr2 = XPath.generate { |x| x.descendant(:div) }
@collection = XPath::Union.new(@expr1, @expr2)
@xpath1 = @collection.where(XPath.attr(:id) == 'foo').to_xpath
@xpath2 = @collection.where(XPath.attr(:id) == 'fooDiv').to_xpath
@results = doc.xpath(@xpath1)
expect(@results[0][:title]).to eq 'fooDiv'
@results = doc.xpath(@xpath2)
expect(@results[0][:id]).to eq 'fooDiv'
end
end
end
| ruby | MIT | 51839ed643d9f28e3df6913fd8ce63fa9379086c | 2026-01-04T17:48:48.612235Z | false |
teamcapybara/xpath | https://github.com/teamcapybara/xpath/blob/51839ed643d9f28e3df6913fd8ce63fa9379086c/spec/xpath_spec.rb | spec/xpath_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'nokogiri'
class Thingy
include XPath
def foo_div
descendant(:div).where(attr(:id) == 'foo')
end
end
describe XPath do
let(:template) { File.read(File.expand_path('fixtures/simple.html', File.dirname(__FILE__))) }
let(:doc) { Nokogiri::HTML(template) }
def xpath(type = nil, &block)
doc.xpath XPath.generate(&block).to_xpath(type)
end
it 'should work as a mixin' do
xpath = Thingy.new.foo_div.to_xpath
expect(doc.xpath(xpath).first[:title]).to eq 'fooDiv'
end
describe '#descendant' do
it 'should find nodes that are nested below the current node' do
@results = xpath { |x| x.descendant(:p) }
expect(@results[0].text).to eq 'Blah'
expect(@results[1].text).to eq 'Bax'
end
it 'should not find nodes outside the context' do
@results = xpath do |x|
foo_div = x.descendant(:div).where(x.attr(:id) == 'foo')
x.descendant(:p).where(x.attr(:id) == foo_div.attr(:title))
end
expect(@results[0]).to be_nil
end
it 'should find multiple kinds of nodes' do
@results = xpath { |x| x.descendant(:p, :ul) }
expect(@results[0].text).to eq 'Blah'
expect(@results[3].text).to eq 'A list'
end
it 'should find all nodes when no arguments given' do
@results = xpath { |x| x.descendant[x.attr(:id) == 'foo'].descendant }
expect(@results[0].text).to eq 'Blah'
expect(@results[4].text).to eq 'A list'
end
end
describe '#child' do
it 'should find nodes that are nested directly below the current node' do
@results = xpath { |x| x.descendant(:div).child(:p) }
expect(@results[0].text).to eq 'Blah'
expect(@results[1].text).to eq 'Bax'
end
it 'should not find nodes that are nested further down below the current node' do
@results = xpath { |x| x.child(:p) }
expect(@results[0]).to be_nil
end
it 'should find multiple kinds of nodes' do
@results = xpath { |x| x.descendant(:div).child(:p, :ul) }
expect(@results[0].text).to eq 'Blah'
expect(@results[3].text).to eq 'A list'
end
it 'should find all nodes when no arguments given' do
@results = xpath { |x| x.descendant[x.attr(:id) == 'foo'].child }
expect(@results[0].text).to eq 'Blah'
expect(@results[3].text).to eq 'A list'
end
end
describe '#axis' do
it 'should find nodes given the xpath axis' do
@results = xpath { |x| x.axis(:descendant, :p) }
expect(@results[0].text).to eq 'Blah'
end
it 'should find nodes given the xpath axis without a specific tag' do
@results = xpath { |x| x.descendant(:div)[x.attr(:id) == 'foo'].axis(:descendant) }
expect(@results[0][:id]).to eq 'fooDiv'
end
end
describe '#next_sibling' do
it 'should find nodes which are immediate siblings of the current node' do
expect(xpath { |x| x.descendant(:p)[x.attr(:id) == 'fooDiv'].next_sibling(:p) }.first.text).to eq 'Bax'
expect(xpath { |x| x.descendant(:p)[x.attr(:id) == 'fooDiv'].next_sibling(:ul, :p) }.first.text).to eq 'Bax'
expect(xpath { |x| x.descendant(:p)[x.attr(:title) == 'monkey'].next_sibling(:ul, :p) }.first.text).to eq 'A list'
expect(xpath { |x| x.descendant(:p)[x.attr(:id) == 'fooDiv'].next_sibling(:ul, :li) }.first).to be_nil
expect(xpath { |x| x.descendant(:p)[x.attr(:id) == 'fooDiv'].next_sibling }.first.text).to eq 'Bax'
end
end
describe '#previous_sibling' do
it 'should find nodes which are exactly preceding the current node' do
expect(xpath { |x| x.descendant(:p)[x.attr(:id) == 'wooDiv'].previous_sibling(:p) }.first.text).to eq 'Bax'
expect(xpath { |x| x.descendant(:p)[x.attr(:id) == 'wooDiv'].previous_sibling(:ul, :p) }.first.text).to eq 'Bax'
expect(xpath { |x| x.descendant(:p)[x.attr(:title) == 'gorilla'].previous_sibling(:ul, :p) }.first.text).to eq 'A list'
expect(xpath { |x| x.descendant(:p)[x.attr(:id) == 'wooDiv'].previous_sibling(:ul, :li) }.first).to be_nil
expect(xpath { |x| x.descendant(:p)[x.attr(:id) == 'wooDiv'].previous_sibling }.first.text).to eq 'Bax'
end
end
describe '#anywhere' do
it 'should find nodes regardless of the context' do
@results = xpath do |x|
foo_div = x.anywhere(:div).where(x.attr(:id) == 'foo')
x.descendant(:p).where(x.attr(:id) == foo_div.attr(:title))
end
expect(@results[0].text).to eq 'Blah'
end
it 'should find multiple kinds of nodes regardless of the context' do
@results = xpath do |x|
context = x.descendant(:div).where(x.attr(:id) == 'woo')
context.anywhere(:p, :ul)
end
expect(@results[0].text).to eq 'Blah'
expect(@results[3].text).to eq 'A list'
expect(@results[4].text).to eq 'A list'
expect(@results[6].text).to eq 'Bax'
end
it 'should find all nodes when no arguments given regardless of the context' do
@results = xpath do |x|
context = x.descendant(:div).where(x.attr(:id) == 'woo')
context.anywhere
end
expect(@results[0].name).to eq 'html'
expect(@results[1].name).to eq 'head'
expect(@results[2].name).to eq 'body'
expect(@results[6].text).to eq 'Blah'
expect(@results[10].text).to eq 'A list'
expect(@results[13].text).to eq 'A list'
expect(@results[15].text).to eq 'Bax'
end
end
describe '#contains' do
it 'should find nodes that contain the given string' do
@results = xpath do |x|
x.descendant(:div).where(x.attr(:title).contains('ooD'))
end
expect(@results[0][:id]).to eq 'foo'
end
it 'should find nodes that contain the given expression' do
@results = xpath do |x|
expression = x.anywhere(:div).where(x.attr(:title) == 'fooDiv').attr(:id)
x.descendant(:div).where(x.attr(:title).contains(expression))
end
expect(@results[0][:id]).to eq 'foo'
end
end
describe '#contains_word' do
it 'should find nodes that contain the given word in its entirety' do
@results = xpath do |x|
x.descendant.where(x.attr(:class).contains_word('fish'))
end
expect(@results[0].text).to eq 'Bax'
expect(@results[1].text).to eq 'llama'
expect(@results.length).to eq 2
end
end
describe '#starts_with' do
it 'should find nodes that begin with the given string' do
@results = xpath do |x|
x.descendant(:*).where(x.attr(:id).starts_with('foo'))
end
expect(@results.size).to eq 2
expect(@results[0][:id]).to eq 'foo'
expect(@results[1][:id]).to eq 'fooDiv'
end
it 'should find nodes that contain the given expression' do
@results = xpath do |x|
expression = x.anywhere(:div).where(x.attr(:title) == 'fooDiv').attr(:id)
x.descendant(:div).where(x.attr(:title).starts_with(expression))
end
expect(@results[0][:id]).to eq 'foo'
end
end
describe '#ends_with' do
it 'should find nodes that end with the given string' do
@results = xpath do |x|
x.descendant(:*).where(x.attr(:id).ends_with('oof'))
end
expect(@results.size).to eq 2
expect(@results[0][:id]).to eq 'oof'
expect(@results[1][:id]).to eq 'viDoof'
end
it 'should find nodes that contain the given expression' do
@results = xpath do |x|
expression = x.anywhere(:div).where(x.attr(:title) == 'viDoof').attr(:id)
x.descendant(:div).where(x.attr(:title).ends_with(expression))
end
expect(@results[0][:id]).to eq 'oof'
end
end
describe '#uppercase' do
it 'should match uppercased text' do
@results = xpath do |x|
x.descendant(:div).where(x.attr(:title).uppercase == 'VIDOOF')
end
expect(@results[0][:id]).to eq 'oof'
end
end
describe '#lowercase' do
it 'should match lowercased text' do
@results = xpath do |x|
x.descendant(:div).where(x.attr(:title).lowercase == 'vidoof')
end
expect(@results[0][:id]).to eq 'oof'
end
end
describe '#text' do
it "should select a node's text" do
@results = xpath { |x| x.descendant(:p).where(x.text == 'Bax') }
expect(@results[0].text).to eq 'Bax'
expect(@results[1][:title]).to eq 'monkey'
@results = xpath { |x| x.descendant(:div).where(x.descendant(:p).text == 'Bax') }
expect(@results[0][:title]).to eq 'fooDiv'
end
end
describe '#substring' do
context 'when called with one argument' do
it 'should select the part of a string after the specified character' do
@results = xpath { |x| x.descendant(:span).where(x.attr(:id) == 'substring').text.substring(7) }
expect(@results).to eq 'there'
end
end
context 'when called with two arguments' do
it 'should select the part of a string after the specified character, up to the given length' do
@results = xpath { |x| x.descendant(:span).where(x.attr(:id) == 'substring').text.substring(2, 4) }
expect(@results).to eq 'ello'
end
end
end
describe '#function' do
it 'should call the given xpath function' do
@results = xpath { |x| x.function(:boolean, x.function(:true) == x.function(:false)) }
expect(@results).to be false
end
end
describe '#method' do
it 'should call the given xpath function with the current node as the first argument' do
@results = xpath { |x| x.descendant(:span).where(x.attr(:id) == 'string-length').text.method(:"string-length") }
expect(@results).to eq 11
end
end
describe '#string_length' do
it 'should return the length of a string' do
@results = xpath { |x| x.descendant(:span).where(x.attr(:id) == 'string-length').text.string_length }
expect(@results).to eq 11
end
end
describe '#where' do
it 'should limit the expression to find only certain nodes' do
expect(xpath { |x| x.descendant(:div).where(:"@id = 'foo'") }.first[:title]).to eq 'fooDiv'
end
it 'should be aliased as []' do
expect(xpath { |x| x.descendant(:div)[:"@id = 'foo'"] }.first[:title]).to eq 'fooDiv'
end
it 'should be a no-op when nil condition is passed' do
expect(XPath.descendant(:div).where(nil).to_s).to eq './/div'
end
end
describe '#inverse' do
it 'should invert the expression' do
expect(xpath { |x| x.descendant(:p).where(x.attr(:id).equals('fooDiv').inverse) }.first.text).to eq 'Bax'
end
it 'should be aliased as the unary tilde' do
expect(xpath { |x| x.descendant(:p).where(~x.attr(:id).equals('fooDiv')) }.first.text).to eq 'Bax'
end
it 'should be aliased as the unary bang' do
expect(xpath { |x| x.descendant(:p).where(!x.attr(:id).equals('fooDiv')) }.first.text).to eq 'Bax'
end
end
describe '#equals' do
it 'should limit the expression to find only certain nodes' do
expect(xpath { |x| x.descendant(:div).where(x.attr(:id).equals('foo')) }.first[:title]).to eq 'fooDiv'
end
it 'should be aliased as ==' do
expect(xpath { |x| x.descendant(:div).where(x.attr(:id) == 'foo') }.first[:title]).to eq 'fooDiv'
end
end
describe '#not_equals' do
it 'should match only when not equal' do
expect(xpath { |x| x.descendant(:div).where(x.attr(:id).not_equals('bar')) }.first[:title]).to eq 'fooDiv'
end
it 'should be aliased as !=' do
expect(xpath { |x| x.descendant(:div).where(x.attr(:id) != 'bar') }.first[:title]).to eq 'fooDiv'
end
end
describe '#is' do
it 'uses equality when :exact given' do
expect(xpath(:exact) { |x| x.descendant(:div).where(x.attr(:id).is('foo')) }.first[:title]).to eq 'fooDiv'
expect(xpath(:exact) { |x| x.descendant(:div).where(x.attr(:id).is('oo')) }.first).to be_nil
end
it 'uses substring matching otherwise' do
expect(xpath { |x| x.descendant(:div).where(x.attr(:id).is('foo')) }.first[:title]).to eq 'fooDiv'
expect(xpath { |x| x.descendant(:div).where(x.attr(:id).is('oo')) }.first[:title]).to eq 'fooDiv'
end
end
describe '#one_of' do
it 'should return all nodes where the condition matches' do
@results = xpath do |x|
p = x.anywhere(:div).where(x.attr(:id) == 'foo').attr(:title)
x.descendant(:*).where(x.attr(:id).one_of('foo', p, 'baz'))
end
expect(@results[0][:title]).to eq 'fooDiv'
expect(@results[1].text).to eq 'Blah'
expect(@results[2][:title]).to eq 'bazDiv'
end
end
describe '#and' do
it 'should find all nodes in both expression' do
@results = xpath do |x|
x.descendant(:*).where(x.contains('Bax').and(x.attr(:title).equals('monkey')))
end
expect(@results[0][:title]).to eq 'monkey'
end
it 'should be aliased as ampersand (&)' do
@results = xpath do |x|
x.descendant(:*).where(x.contains('Bax') & x.attr(:title).equals('monkey'))
end
expect(@results[0][:title]).to eq 'monkey'
end
end
describe '#or' do
it 'should find all nodes in either expression' do
@results = xpath do |x|
x.descendant(:*).where(x.attr(:id).equals('foo').or(x.attr(:id).equals('fooDiv')))
end
expect(@results[0][:title]).to eq 'fooDiv'
expect(@results[1].text).to eq 'Blah'
end
it 'should be aliased as pipe (|)' do
@results = xpath do |x|
x.descendant(:*).where(x.attr(:id).equals('foo') | x.attr(:id).equals('fooDiv'))
end
expect(@results[0][:title]).to eq 'fooDiv'
expect(@results[1].text).to eq 'Blah'
end
end
describe '#attr' do
it 'should be an attribute' do
@results = xpath { |x| x.descendant(:div).where(x.attr(:id)) }
expect(@results[0][:title]).to eq 'barDiv'
expect(@results[1][:title]).to eq 'fooDiv'
end
end
describe '#css' do
it 'should find nodes by the given CSS selector' do
@results = xpath { |x| x.css('#preference p') }
expect(@results[0].text).to eq 'allamas'
expect(@results[1].text).to eq 'llama'
end
it 'should respect previous expression' do
@results = xpath { |x| x.descendant[x.attr(:id) == 'moar'].css('p') }
expect(@results[0].text).to eq 'chimp'
expect(@results[1].text).to eq 'flamingo'
end
it 'should be composable' do
@results = xpath { |x| x.css('#moar').descendant(:p) }
expect(@results[0].text).to eq 'chimp'
expect(@results[1].text).to eq 'flamingo'
end
it 'should allow comma separated selectors' do
@results = xpath { |x| x.descendant[x.attr(:id) == 'moar'].css('div, p') }
expect(@results[0].text).to eq 'chimp'
expect(@results[1].text).to eq 'elephant'
expect(@results[2].text).to eq 'flamingo'
end
end
describe '#qname' do
it "should match the node's name" do
expect(xpath { |x| x.descendant(:*).where(x.qname == 'ul') }.first.text).to eq 'A list'
end
end
describe '#union' do
it 'should create a union expression' do
@expr1 = XPath.generate { |x| x.descendant(:p) }
@expr2 = XPath.generate { |x| x.descendant(:div) }
@collection = @expr1.union(@expr2)
@xpath1 = @collection.where(XPath.attr(:id) == 'foo').to_xpath
@xpath2 = @collection.where(XPath.attr(:id) == 'fooDiv').to_xpath
@results = doc.xpath(@xpath1)
expect(@results[0][:title]).to eq 'fooDiv'
@results = doc.xpath(@xpath2)
expect(@results[0][:id]).to eq 'fooDiv'
end
it 'should be aliased as +' do
@expr1 = XPath.generate { |x| x.descendant(:p) }
@expr2 = XPath.generate { |x| x.descendant(:div) }
@collection = @expr1 + @expr2
@xpath1 = @collection.where(XPath.attr(:id) == 'foo').to_xpath
@xpath2 = @collection.where(XPath.attr(:id) == 'fooDiv').to_xpath
@results = doc.xpath(@xpath1)
expect(@results[0][:title]).to eq 'fooDiv'
@results = doc.xpath(@xpath2)
expect(@results[0][:id]).to eq 'fooDiv'
end
end
describe '#last' do
it 'returns the number of elements in the context' do
@results = xpath { |x| x.descendant(:p)[XPath.position == XPath.last] }
expect(@results[0].text).to eq 'Bax'
expect(@results[1].text).to eq 'Blah'
expect(@results[2].text).to eq 'llama'
end
end
describe '#position' do
it 'returns the position of elements in the context' do
@results = xpath { |x| x.descendant(:p)[XPath.position == 2] }
expect(@results[0].text).to eq 'Bax'
expect(@results[1].text).to eq 'Bax'
end
end
describe '#count' do
it 'counts the number of occurrences' do
@results = xpath { |x| x.descendant(:div)[x.descendant(:p).count == 2] }
expect(@results[0][:id]).to eq 'preference'
end
end
describe '#lte' do
it 'checks lesser than or equal' do
@results = xpath { |x| x.descendant(:p)[XPath.position <= 2] }
expect(@results[0].text).to eq 'Blah'
expect(@results[1].text).to eq 'Bax'
expect(@results[2][:title]).to eq 'gorilla'
expect(@results[3].text).to eq 'Bax'
end
end
describe '#lt' do
it 'checks lesser than' do
@results = xpath { |x| x.descendant(:p)[XPath.position < 2] }
expect(@results[0].text).to eq 'Blah'
expect(@results[1][:title]).to eq 'gorilla'
end
end
describe '#gte' do
it 'checks greater than or equal' do
@results = xpath { |x| x.descendant(:p)[XPath.position >= 2] }
expect(@results[0].text).to eq 'Bax'
expect(@results[1][:title]).to eq 'monkey'
expect(@results[2].text).to eq 'Bax'
expect(@results[3].text).to eq 'Blah'
end
end
describe '#gt' do
it 'checks greater than' do
@results = xpath { |x| x.descendant(:p)[XPath.position > 2] }
expect(@results[0][:title]).to eq 'monkey'
expect(@results[1].text).to eq 'Blah'
end
end
describe '#plus' do
it 'adds stuff' do
@results = xpath { |x| x.descendant(:p)[XPath.position.plus(1) == 2] }
expect(@results[0][:id]).to eq 'fooDiv'
expect(@results[1][:title]).to eq 'gorilla'
end
end
describe '#minus' do
it 'subtracts stuff' do
@results = xpath { |x| x.descendant(:p)[XPath.position.minus(1) == 0] }
expect(@results[0][:id]).to eq 'fooDiv'
expect(@results[1][:title]).to eq 'gorilla'
end
end
describe '#multiply' do
it 'multiplies stuff' do
@results = xpath { |x| x.descendant(:p)[XPath.position * 3 == 3] }
expect(@results[0][:id]).to eq 'fooDiv'
expect(@results[1][:title]).to eq 'gorilla'
end
end
describe '#divide' do
it 'divides stuff' do
@results = xpath { |x| x.descendant(:p)[XPath.position / 2 == 1] }
expect(@results[0].text).to eq 'Bax'
expect(@results[1].text).to eq 'Bax'
end
end
describe '#mod' do
it 'take modulo' do
@results = xpath { |x| x.descendant(:p)[XPath.position % 2 == 1] }
expect(@results[0].text).to eq 'Blah'
expect(@results[1][:title]).to eq 'monkey'
expect(@results[2][:title]).to eq 'gorilla'
end
end
describe '#ancestor' do
it 'finds ancestor nodes' do
@results = xpath { |x| x.descendant(:p)[1].ancestor }
expect(@results[0].node_name).to eq 'html'
expect(@results[1].node_name).to eq 'body'
expect(@results[2][:id]).to eq 'foo'
end
end
end
| ruby | MIT | 51839ed643d9f28e3df6913fd8ce63fa9379086c | 2026-01-04T17:48:48.612235Z | false |
teamcapybara/xpath | https://github.com/teamcapybara/xpath/blob/51839ed643d9f28e3df6913fd8ce63fa9379086c/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
require 'xpath'
require 'pry'
| ruby | MIT | 51839ed643d9f28e3df6913fd8ce63fa9379086c | 2026-01-04T17:48:48.612235Z | false |
teamcapybara/xpath | https://github.com/teamcapybara/xpath/blob/51839ed643d9f28e3df6913fd8ce63fa9379086c/lib/xpath.rb | lib/xpath.rb | # frozen_string_literal: true
require 'nokogiri'
require 'xpath/dsl'
require 'xpath/expression'
require 'xpath/literal'
require 'xpath/union'
require 'xpath/renderer'
module XPath
extend XPath::DSL
include XPath::DSL
def self.generate
yield(self)
end
end
| ruby | MIT | 51839ed643d9f28e3df6913fd8ce63fa9379086c | 2026-01-04T17:48:48.612235Z | false |
teamcapybara/xpath | https://github.com/teamcapybara/xpath/blob/51839ed643d9f28e3df6913fd8ce63fa9379086c/lib/xpath/version.rb | lib/xpath/version.rb | # frozen_string_literal: true
module XPath
VERSION = '3.2.0'
end
| ruby | MIT | 51839ed643d9f28e3df6913fd8ce63fa9379086c | 2026-01-04T17:48:48.612235Z | false |
teamcapybara/xpath | https://github.com/teamcapybara/xpath/blob/51839ed643d9f28e3df6913fd8ce63fa9379086c/lib/xpath/literal.rb | lib/xpath/literal.rb | # frozen_string_literal: true
module XPath
class Literal
attr_reader :value
def initialize(value)
@value = value
end
end
end
| ruby | MIT | 51839ed643d9f28e3df6913fd8ce63fa9379086c | 2026-01-04T17:48:48.612235Z | false |
teamcapybara/xpath | https://github.com/teamcapybara/xpath/blob/51839ed643d9f28e3df6913fd8ce63fa9379086c/lib/xpath/dsl.rb | lib/xpath/dsl.rb | # frozen_string_literal: true
module XPath
module DSL
def current
Expression.new(:this_node)
end
def descendant(*expressions)
Expression.new(:descendant, current, expressions)
end
def child(*expressions)
Expression.new(:child, current, expressions)
end
def axis(name, *element_names)
Expression.new(:axis, current, name, element_names)
end
def anywhere(*expressions)
Expression.new(:anywhere, expressions)
end
def attr(expression)
Expression.new(:attribute, current, expression)
end
def text
Expression.new(:text, current)
end
def css(selector)
Expression.new(:css, current, Literal.new(selector))
end
def function(name, *arguments)
Expression.new(:function, name, *arguments)
end
def method(name, *arguments)
Expression.new(:function, name, current, *arguments)
end
def where(expression)
if expression
Expression.new(:where, current, expression)
else
current
end
end
alias_method :[], :where
def is(expression)
Expression.new(:is, current, expression)
end
def binary_operator(name, rhs)
Expression.new(:binary_operator, name, current, rhs)
end
def union(*expressions)
Union.new(*[self, expressions].flatten)
end
alias_method :+, :union
def last
function(:last)
end
def position
function(:position)
end
METHODS = [
# node set
:count, :id, :local_name, :namespace_uri,
# string
:string, :concat, :starts_with, :contains, :substring_before,
:substring_after, :substring, :string_length, :normalize_space,
:translate,
# boolean
:boolean, :not, :true, :false, :lang,
# number
:number, :sum, :floor, :ceiling, :round
].freeze
METHODS.each do |key|
name = key.to_s.tr('_', '-').to_sym
define_method key do |*args|
method(name, *args)
end
end
def qname
method(:name)
end
alias_method :inverse, :not
alias_method :~, :not
alias_method :!, :not
alias_method :normalize, :normalize_space
alias_method :n, :normalize_space
OPERATORS = [
%i[equals = ==],
%i[or or |],
%i[and and &],
%i[not_equals != !=],
%i[lte <= <=],
%i[lt < <],
%i[gte >= >=],
%i[gt > >],
%i[plus +],
%i[minus -],
%i[multiply * *],
%i[divide div /],
%i[mod mod %]
].freeze
OPERATORS.each do |(name, operator, alias_name)|
define_method name do |rhs|
binary_operator(operator, rhs)
end
alias_method alias_name, name if alias_name
end
AXES = %i[
ancestor ancestor_or_self attribute descendant_or_self
following following_sibling namespace parent preceding
preceding_sibling self
].freeze
AXES.each do |key|
name = key.to_s.tr('_', '-').to_sym
define_method key do |*element_names|
axis(name, *element_names)
end
end
alias_method :self_axis, :self
def ends_with(suffix)
function(:substring, current, function(:'string-length', current).minus(function(:'string-length', suffix)).plus(1)) == suffix
end
def contains_word(word)
function(:concat, ' ', current.normalize_space, ' ').contains(" #{word} ")
end
UPPERCASE_LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞŸŽŠŒ'
LOWERCASE_LETTERS = 'abcdefghijklmnopqrstuvwxyzàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿžšœ'
def lowercase
method(:translate, UPPERCASE_LETTERS, LOWERCASE_LETTERS)
end
def uppercase
method(:translate, LOWERCASE_LETTERS, UPPERCASE_LETTERS)
end
def one_of(*expressions)
expressions.map { |e| current.equals(e) }.reduce(:or)
end
def next_sibling(*expressions)
axis(:"following-sibling")[1].axis(:self, *expressions)
end
def previous_sibling(*expressions)
axis(:"preceding-sibling")[1].axis(:self, *expressions)
end
end
end
| ruby | MIT | 51839ed643d9f28e3df6913fd8ce63fa9379086c | 2026-01-04T17:48:48.612235Z | false |
teamcapybara/xpath | https://github.com/teamcapybara/xpath/blob/51839ed643d9f28e3df6913fd8ce63fa9379086c/lib/xpath/union.rb | lib/xpath/union.rb | # frozen_string_literal: true
module XPath
class Union
include Enumerable
attr_reader :expressions
alias_method :arguments, :expressions
def initialize(*expressions)
@expressions = expressions
end
def expression
:union
end
def each(&)
arguments.each(&)
end
def method_missing(*args) # rubocop:disable Style/MissingRespondToMissing
XPath::Union.new(*arguments.map { |e| e.send(*args) })
end
def to_xpath(type = nil)
Renderer.render(self, type)
end
alias_method :to_s, :to_xpath
end
end
| ruby | MIT | 51839ed643d9f28e3df6913fd8ce63fa9379086c | 2026-01-04T17:48:48.612235Z | false |
teamcapybara/xpath | https://github.com/teamcapybara/xpath/blob/51839ed643d9f28e3df6913fd8ce63fa9379086c/lib/xpath/renderer.rb | lib/xpath/renderer.rb | # frozen_string_literal: true
module XPath
class Renderer
def self.render(node, type)
new(type).render(node)
end
def initialize(type)
@type = type
end
def render(node)
arguments = node.arguments.map { |argument| convert_argument(argument) }
send(node.expression, *arguments)
end
def convert_argument(argument)
case argument
when Expression, Union then render(argument)
when Array then argument.map { |element| convert_argument(element) }
when String then string_literal(argument)
when Literal then argument.value
else argument.to_s
end
end
def string_literal(string)
if string.include?("'")
string = string.split("'", -1).map do |substr|
"'#{substr}'"
end.join(%q(,"'",))
"concat(#{string})"
else
"'#{string}'"
end
end
def this_node
'.'
end
def descendant(current, element_names)
with_element_conditions("#{current}//", element_names)
end
def child(current, element_names)
with_element_conditions("#{current}/", element_names)
end
def axis(current, name, element_names)
with_element_conditions("#{current}/#{name}::", element_names)
end
def anywhere(element_names)
with_element_conditions('//', element_names)
end
def where(on, condition)
"#{on}[#{condition}]"
end
def attribute(current, name)
if valid_xml_name?(name)
"#{current}/@#{name}"
else
"#{current}/attribute::*[local-name(.) = #{string_literal(name)}]"
end
end
def binary_operator(name, left, right)
"(#{left} #{name} #{right})"
end
def is(one, two)
if @type == :exact
binary_operator('=', one, two)
else
function(:contains, one, two)
end
end
def variable(name)
"%{#{name}}"
end
def text(current)
"#{current}/text()"
end
def literal(node)
node
end
def css(current, selector)
paths = Nokogiri::CSS.xpath_for(selector).map do |xpath_selector|
"#{current}#{xpath_selector}"
end
union(paths)
end
def union(*expressions)
expressions.join(' | ')
end
def function(name, *arguments)
"#{name}(#{arguments.join(', ')})"
end
private
def with_element_conditions(expression, element_names)
if element_names.length == 1
"#{expression}#{element_names.first}"
elsif element_names.length > 1
"#{expression}*[#{element_names.map { |e| "self::#{e}" }.join(' | ')}]"
else
"#{expression}*"
end
end
def valid_xml_name?(name)
name =~ /^[a-zA-Z_:][a-zA-Z0-9_:.-]*$/
end
end
end
| ruby | MIT | 51839ed643d9f28e3df6913fd8ce63fa9379086c | 2026-01-04T17:48:48.612235Z | false |
teamcapybara/xpath | https://github.com/teamcapybara/xpath/blob/51839ed643d9f28e3df6913fd8ce63fa9379086c/lib/xpath/expression.rb | lib/xpath/expression.rb | # frozen_string_literal: true
module XPath
class Expression
attr_accessor :expression, :arguments
include XPath::DSL
def initialize(expression, *arguments)
@expression = expression
@arguments = arguments
end
def current
self
end
def to_xpath(type = nil)
Renderer.render(self, type)
end
alias_method :to_s, :to_xpath
end
end
| ruby | MIT | 51839ed643d9f28e3df6913fd8ce63fa9379086c | 2026-01-04T17:48:48.612235Z | false |
lostfilm/books-dl | https://github.com/lostfilm/books-dl/blob/8507e48c2d788c1c8233ba81c6952eaace848f5b/main.rb | main.rb | require_relative './lib/books_dl'
# 如何取得 book_id
# 進入你要下載的書的閱讀頁面,取得網址列中網址
# 例如:
# https://viewer-ebook.books.com.tw/viewer/epub/web/?book_uni_id=E050017049_reflowable_normal
# book_uni_id= 之後的字串就是這本書的 book_id 了
#
book_id = 'E050017049_reflowable_normal'
downloader = BooksDL::Downloader.new(book_id)
downloader.perform
book_id = 'E050013173_reflowable_normal'
downloader = BooksDL::Downloader.new(book_id)
downloader.perform | ruby | MIT | 8507e48c2d788c1c8233ba81c6952eaace848f5b | 2026-01-04T17:48:51.215079Z | false |
lostfilm/books-dl | https://github.com/lostfilm/books-dl/blob/8507e48c2d788c1c8233ba81c6952eaace848f5b/spec/helpers.rb | spec/helpers.rb | module Helpers
RSPEC_ROOT_PATH = "#{__FILE__.split('/spec/').first}/spec".freeze
def file_fixture(file_name)
file_path = File.join(RSPEC_ROOT_PATH, 'fixtures', 'files', file_name)
File.open(file_path)
end
end
| ruby | MIT | 8507e48c2d788c1c8233ba81c6952eaace848f5b | 2026-01-04T17:48:51.215079Z | false |
lostfilm/books-dl | https://github.com/lostfilm/books-dl/blob/8507e48c2d788c1c8233ba81c6952eaace848f5b/spec/spec_helper.rb | spec/spec_helper.rb | # Load lib
require_relative '../lib/books_dl'
require_relative './helpers'
# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
config.include Helpers
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching :focus
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# This setting enables warnings. It's recommended, but in some cases may
# be too noisy due to issues in dependencies.
config.warnings = true
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = "doc"
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end
| ruby | MIT | 8507e48c2d788c1c8233ba81c6952eaace848f5b | 2026-01-04T17:48:51.215079Z | false |
lostfilm/books-dl | https://github.com/lostfilm/books-dl/blob/8507e48c2d788c1c8233ba81c6952eaace848f5b/spec/books_dl/utils_spec.rb | spec/books_dl/utils_spec.rb | describe BooksDL::Utils do
let(:download_token) { file_fixture('download_token.txt').read }
let(:url) { 'https://streaming-ebook.books.com.tw/V1.0/Streaming/book/DD0CB3/952170/OEBPS/content.opf' }
let(:url2) { 'https://streaming-ebook.books.com.tw/V1.0/Streaming/book/DD0CB3/952170/META-INF/container.xml' }
describe '.hex_to_byte' do
let(:hex) { 'ABCDEFG987654321' }
let(:bytes_array) { [171, 205, 239, 0, 135, 101, 67, 33] }
it 'return empty array when input is nil' do
return_value = described_class.hex_to_byte(nil)
expect(return_value).to be_a Array
expect(return_value).to be_empty
end
it 'return byte array correctly' do
return_value = described_class.hex_to_byte(hex)
expect(return_value).to be_a Array
expect(return_value).to eq bytes_array
end
end
describe '.generate_key' do
let(:decode) { [101, 87, 67, 247, 38, 70, 65, 140, 139, 83, 14, 193, 211, 197, 38, 225, 48, 35, 79, 108, 47, 47, 191, 253, 44, 205, 93, 130, 226, 96, 203, 82] }
let(:decode2) { [125, 142, 71, 182, 184, 151, 206, 229, 41, 53, 224, 96, 131, 141, 200, 22, 28, 118, 85, 249, 243, 74, 28, 193, 218, 219, 4, 243, 201, 221, 108, 117] }
it 'return decode bytes array' do
return_value = described_class.generate_key(url, download_token)
expect(return_value).to be_a Array
expect(return_value).to eq decode
end
it 'return decode2 bytes array' do
return_value = described_class.generate_key(url2, download_token)
expect(return_value).to be_a Array
expect(return_value).to eq decode2
end
end
describe '.decode_xor' do
let(:key) { described_class.generate_key(url, download_token) }
let(:encrypted_content_opf) { file_fixture('encrypted_content.opf').read }
let(:content_opf) { file_fixture('content.opf').read }
let(:key2) { described_class.generate_key(url2, download_token) }
let(:encrypted_container_xml) { file_fixture('encrypted_container.xml').read }
let(:container_xml) { file_fixture('container.xml').read }
it 'return decoded content opf' do
return_value = described_class.decode_xor(key, encrypted_content_opf)
expect(return_value).to eq content_opf
end
it 'return decoded container.xml' do
return_value = described_class.decode_xor(key2, encrypted_container_xml)
expect(return_value).to eq container_xml
end
end
end
| ruby | MIT | 8507e48c2d788c1c8233ba81c6952eaace848f5b | 2026-01-04T17:48:51.215079Z | false |
lostfilm/books-dl | https://github.com/lostfilm/books-dl/blob/8507e48c2d788c1c8233ba81c6952eaace848f5b/lib/books_dl.rb | lib/books_dl.rb | require 'rubygems'
require 'bundler'
require 'json'
require 'digest'
require 'io/console'
require 'ostruct'
Bundler.require(:default)
module BooksDL; end
Dir[File.join(__dir__, 'books_dl', '**', '*.rb')].each(&method(:require))
| ruby | MIT | 8507e48c2d788c1c8233ba81c6952eaace848f5b | 2026-01-04T17:48:51.215079Z | false |
lostfilm/books-dl | https://github.com/lostfilm/books-dl/blob/8507e48c2d788c1c8233ba81c6952eaace848f5b/lib/books_dl/utils.rb | lib/books_dl/utils.rb | module BooksDL
class Utils
def self.hex_to_byte(hex)
return [] unless hex.is_a?(String)
hex.scan(/../).map(&:hex)
end
def self.generate_key(url, download_token)
puts url
file_path = CGI.unescape(url.match(%r|https://(.*?/){3}.*?(?<rest_part>/.+)|)[:rest_part])
md5_chars = Digest::MD5.hexdigest(file_path).split('')
partition = md5_chars.each_slice(4).reduce(0) do |num, chars|
(num + Integer("0x#{chars.join}")) % 64
end
decode_hex = Digest::SHA256.hexdigest("#{download_token[0...partition]}#{file_path}#{download_token[partition..]}")
hex_to_byte(decode_hex)
end
def self.decode_xor(key, encrypted_content)
count = 0
tmp = []
bytes = encrypted_content.bytes
(0...bytes.size).each do |idx|
tmp[idx] = bytes[idx] ^ key[count]
count += 1
count = 0 if count >= key.size
end
tmp = tmp[3..] if (tmp[0] == 239) && (tmp[1] == 187) && (tmp[2] == 191)
result = if tmp.size > 10_000
count2 = (tmp.size / 10_000.0).ceil
(0...count2).each do |idx|
tmp[idx] = tmp[idx * 10_000...(idx + 1) * 10_000]
end
tmp[0...count2].reduce('') { |str, bytes| str << bytes.pack('c*') }
else
tmp.pack('c*')
end
result.force_encoding('utf-8')
end
def self.img_checksum
seed = %w[0 6 9 3 1 4 7 1 8 0 5 5 9 A A C]
(0...seed.size).each do |idx|
rand_idx = (0...seed.size).to_a.sample
seed[idx], seed[rand_idx] = seed[rand_idx], seed[idx]
end
seed.join
end
end
end
| ruby | MIT | 8507e48c2d788c1c8233ba81c6952eaace848f5b | 2026-01-04T17:48:51.215079Z | false |
lostfilm/books-dl | https://github.com/lostfilm/books-dl/blob/8507e48c2d788c1c8233ba81c6952eaace848f5b/lib/books_dl/api.rb | lib/books_dl/api.rb | module BooksDL
class API
attr_reader :current_cookie, :book_id, :encoded_token
COOKIE_FILE_NAME = 'cookie.json'.freeze
IMAGE_EXTENSIONS = %w[.bmp .gif .ico .jpeg .jpg .tiff .tif .svg .png .webp].freeze
NO_AUTH_EXTENSIONS = %w[.css .ttc .otf .ttf .eot .woff .woff2].freeze
# API ENDPOINTS
#
# rubocop:disable Metrics/LineLength
CART_URL = 'https://db.books.com.tw/shopping/cart_list.php'.freeze
LOGIN_HOST = 'https://cart.books.com.tw'.freeze
LOGIN_PAGE_URL = "https://cart.books.com.tw/member/login?url=#{CART_URL}".freeze
LOGIN_ENDPOINT_URL = 'https://cart.books.com.tw/member/login_do/'.freeze
DEVICE_REG_URL = 'https://appapi-ebook.books.com.tw/V1.3/CMSAPIApp/DeviceReg'.freeze
OAUTH_URL = 'https://appapi-ebook.books.com.tw/V1.3/CMSAPIApp/LoginURL?type=&device_id=&redirect_uri=https%3A%2F%2Fviewer-ebook.books.com.tw%2Fviewer%2Flogin.html'.freeze
OAUTH_ENDPOINT_URL = 'https://appapi-ebook.books.com.tw/V1.3/CMSAPIApp/MemberLogin?code='.freeze
BOOK_DL_URL = 'https://appapi-ebook.books.com.tw/V1.3/CMSAPIApp/BookDownLoadURL'.freeze
# rubocop:enable Metrics/LineLength
def initialize(book_id)
@book_id = book_id
load_existed_cookies
@encoded_token ||= CGI.escape(info.download_token.to_s)
end
def fetch(path)
url = "#{info.download_link}#{path}"
ext = File.extname(path).downcase
if NO_AUTH_EXTENSIONS.include?(ext) || info.encrypt_type == 'none'
get(url).body.to_s
elsif IMAGE_EXTENSIONS.include?(ext)
checksum = Utils.img_checksum
resp = get("#{url}?checksum=#{checksum}&DownloadToken=#{encoded_token}")
resp.body.to_s
else
key = Utils.generate_key(url, info.download_token)
resp = get("#{url}?DownloadToken=#{encoded_token}")
Utils.decode_xor(key, resp.body.to_s)
end
end
# return Struct of [:book_uni_id, :download_link, :download_token, :size, :encrypt_type]
def info
@info ||= begin
login
data = {
form: {
device_id: '2b2475e7-da58-4cfe-aedf-ab4e6463757b',
language: 'zh-TW',
os_type: 'WEB',
os_version: default_headers[:'user-agent'],
screen_resolution: '1680X1050',
screen_dpi: 96,
device_vendor: 'Google Inc.',
device_model: 'web'
}
}
headers = {
accept: 'application/json, text/javascript, */*; q=0.01',
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
Origin: 'https://viewer-ebook.books.com.tw',
Referer: 'https://viewer-ebook.books.com.tw/viewer/epub/web/?book_uni_id=E050017049_reflowable_normal',
}
# remove old cookies
current_cookie.reject! { |key| %w[CmsToken redirect_uri normal_redirect_uri DownloadToken].include?(key) }
puts '註冊 Fake device 中...'
post(DEVICE_REG_URL, data, headers)
puts '透過 OAuth 取得 CmsToken...'
resp = get(OAUTH_URL)
login_uri = JSON.parse(resp.body.to_s).fetch('login_uri')
code = get(login_uri).headers['Location'].split('&code=').last
get("#{OAUTH_ENDPOINT_URL}#{code}")
resp = get("#{BOOK_DL_URL}?book_uni_id=#{book_id}&t=#{Time.now.to_i}")
OpenStruct.new(JSON.parse(resp.body.to_s))
end
end
def login
return if logged?
username, password = get_account_from_stdin
login_page = get(LOGIN_PAGE_URL).body.to_s
captcha = get_captcha_from(login_page)
data = { form: { captcha: captcha, login_id: username, login_pswd: password } }
headers = {
'Host': 'cart.books.com.tw',
'Referer': 'https://cart.books.com.tw/member/login',
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
}
post(LOGIN_ENDPOINT_URL, data, headers)
return if logged?
puts "#{'-' * 10} 登入失敗,請再試一次 #{'-' * 10}\n"
login
end
def logged?
@logged = begin
response = get(CART_URL)
response.status == 200
end
end
private
def load_existed_cookies
@current_cookie = JSON.parse(File.read(COOKIE_FILE_NAME))
rescue StandardError
@current_cookie = {}
end
def get_account_from_stdin
print('請輸入帳號:')
username = gets.chomp
password = STDIN.getpass('請輸入密碼:').chomp
[username, password]
end
def get(url, headers = {})
headers = build_headers({ Cookie: cookie }, headers)
response = HTTP.headers(headers).get(url)
if response.status >= 400
file_name = URI(url).path.split('/').last
raise "取得 `#{file_name}` 失敗。 Status: #{response.status}"
end
save_cookie(response)
response
end
def post(url, data = {}, headers = {})
headers = build_headers({ Cookie: cookie }, headers)
response = HTTP.headers(headers).post(url, data)
save_cookie(response)
response
end
def save_cookie(response)
cookie_jar = response.cookies
cookie_hash = cookie_jar.map { |cookie| [cookie.name, cookie.value] }.to_h
current_cookie.merge!(cookie_hash)
cookie_json = JSON.pretty_generate(current_cookie)
File.open(COOKIE_FILE_NAME, 'w') do |file|
file.write(cookie_json)
end
end
def cookie
current_cookie.reduce('') { |cookie, (name, value)| cookie + "#{name}=#{value}; " }.strip
end
def default_headers
@default_headers ||= {
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) ' \
'AppleWebKit/537.36 (KHTML, like Gecko) ' \
'Chrome/71.0.3578.98 Safari/537.36'
}
end
def build_headers(*args)
args.reduce(default_headers, &:merge)
end
def get_user_input(label)
puts label
gets.chomp
end
def get_captcha_from(login_page)
doc = Nokogiri::HTML(login_page)
captcha_img_path = doc.at_css('#captcha_img > img').attr('src')
captcha_img_url = "#{LOGIN_HOST}#{captcha_img_path}"
img = get(captcha_img_url).body
File.open('captcha.png', 'wb+') { |file| file.write(img) }
begin
`open ./captcha.png`
rescue StandardError
puts '開啟失敗,請自行查看 captcha.png 檔案。'
end
puts '請輸入認證碼 (captcha.png,不分大小寫):'
gets.chomp
end
end
end
| ruby | MIT | 8507e48c2d788c1c8233ba81c6952eaace848f5b | 2026-01-04T17:48:51.215079Z | false |
lostfilm/books-dl | https://github.com/lostfilm/books-dl/blob/8507e48c2d788c1c8233ba81c6952eaace848f5b/lib/books_dl/base_file.rb | lib/books_dl/base_file.rb | module BooksDL
class BaseFile
attr_reader :path, :content
def initialize(path, content)
@path = path
@content = content
end
end
end | ruby | MIT | 8507e48c2d788c1c8233ba81c6952eaace848f5b | 2026-01-04T17:48:51.215079Z | false |
lostfilm/books-dl | https://github.com/lostfilm/books-dl/blob/8507e48c2d788c1c8233ba81c6952eaace848f5b/lib/books_dl/downloader.rb | lib/books_dl/downloader.rb | require 'zip'
module BooksDL
class Downloader
attr_reader :api, :book, :book_id, :info
def initialize(book_id)
@book_id = book_id
@api = API.new(book_id)
@book = {
root_file_path: nil,
root_file: nil,
files: [
::BooksDL::BaseFile.new('mimetype', 'application/epub+zip')
]
}
end
def perform
job('取得 META-INF/container.xml') { fetch_container_file }
job('取得 META-INF/encryption.xml') { fetch_encryption_file }
job("取得 #{book[:root_file_path]} 檔案") { fetch_root_file }
fetch_book_content # 由內部顯示 job 訊息
job('製作 epub 檔案') { build_epub }
puts "#{book_id} 下載完成"
end
private
def job(name)
print "正在#{name}..."
puts '成功' if yield
end
def fetch_container_file
path = 'META-INF/container.xml'
content = api.fetch(path)
container_file = Files::Container.new(path, content)
book[:root_file_path] = container_file.root_file_path
book[:files] << container_file
end
def fetch_encryption_file
path = 'META-INF/encryption.xml'
content = api.fetch(path)
encryption_file = BaseFile.new(path, content)
book[:files] << encryption_file
rescue StandardError => e
puts "\n#{e}"
puts "Just a encryption file, it doesn't matter..."
false
end
def fetch_root_file
path = book[:root_file_path]
content = api.fetch(path)
root_file = Files::Content.new(path, content)
book[:root_file] = root_file
book[:files] << root_file
end
def fetch_book_content
root_file = book[:root_file]
file_paths = root_file.file_paths
total = file_paths.size
file_paths.each_with_index do |path, index|
puts "#{index + 1}/#{total} => 開始下載 #{path}"
content = api.fetch(path)
book[:files] << BaseFile.new(path, content)
end
end
def build_epub
title = book[:root_file].title
files = book[:files]
filename = "#{book_id}_#{title}.epub"
::Zip::File.open(filename, ::Zip::File::CREATE) do |zipfile|
files.each do |file|
zipfile.get_output_stream(file.path) { |zip| zip.write(file.content) }
end
end
end
end
end | ruby | MIT | 8507e48c2d788c1c8233ba81c6952eaace848f5b | 2026-01-04T17:48:51.215079Z | false |
lostfilm/books-dl | https://github.com/lostfilm/books-dl/blob/8507e48c2d788c1c8233ba81c6952eaace848f5b/lib/books_dl/files/content.rb | lib/books_dl/files/content.rb | module BooksDL
module Files
class Content < ::BooksDL::BaseFile
def file_paths
doc.css('item').map do |item|
::File.join(base_dir, item.attr('href')).to_s
end
end
def title
doc.remove_namespaces!
.css('title')
.first
.text
end
private
# OEBPS/content.opf => OEBPS
def base_dir
::File.dirname(path)
end
def doc
Nokogiri::XML(content)
end
end
end
end | ruby | MIT | 8507e48c2d788c1c8233ba81c6952eaace848f5b | 2026-01-04T17:48:51.215079Z | false |
lostfilm/books-dl | https://github.com/lostfilm/books-dl/blob/8507e48c2d788c1c8233ba81c6952eaace848f5b/lib/books_dl/files/container.rb | lib/books_dl/files/container.rb | module BooksDL
module Files
class Container < ::BooksDL::BaseFile
def root_file_path
doc.css('rootfile').first.attr('full-path')
end
private
def doc
Nokogiri::XML(content)
end
end
end
end | ruby | MIT | 8507e48c2d788c1c8233ba81c6952eaace848f5b | 2026-01-04T17:48:51.215079Z | false |
isaacsanders/omniauth-stripe-connect | https://github.com/isaacsanders/omniauth-stripe-connect/blob/468dd9acaccdbba38a38cdbcdf7f10c17be25e89/spec/spec_helper.rb | spec/spec_helper.rb | require 'rspec'
require 'omniauth-stripe-connect'
| ruby | MIT | 468dd9acaccdbba38a38cdbcdf7f10c17be25e89 | 2026-01-04T17:48:51.752026Z | false |
isaacsanders/omniauth-stripe-connect | https://github.com/isaacsanders/omniauth-stripe-connect/blob/468dd9acaccdbba38a38cdbcdf7f10c17be25e89/spec/omniauth/strategies/stripe_connect_spec.rb | spec/omniauth/strategies/stripe_connect_spec.rb | require 'spec_helper'
describe OmniAuth::Strategies::StripeConnect do
let(:fresh_strategy) { Class.new(OmniAuth::Strategies::StripeConnect) }
before(:each) do
OmniAuth.config.test_mode = true
@old_host = OmniAuth.config.full_host
end
after(:each) do
OmniAuth.config.full_host = @old_host
OmniAuth.config.test_mode = false
end
describe '#authorize_params' do
subject { fresh_strategy }
it 'should include redirect_uri if full_host is set' do
OmniAuth.config.full_host = 'https://foo.com/'
instance = subject.new('abc', 'def')
instance.authorize_params[:redirect_uri].should =~ /\Ahttps:\/\/foo\.com/
end
it 'should include redirect_uri if callback_path is set' do
# TODO: It would be nice to grab this from the request URL
# instead of setting it on the config
OmniAuth.config.full_host = 'https://foo.com/'
instance = subject.new('abc', 'def', :callback_path => 'bar/baz')
instance.authorize_params[:redirect_uri].should == 'https://foo.com/bar/baz'
end
it 'should not include redirect_uri by default' do
instance = subject.new('abc', 'def')
expect(instance.authorize_params[:redirect_uri]).to be_nil
end
end
describe '#token_params' do
subject { fresh_strategy }
# NOTE: We call authorize_params first in each of these methods
# since the OAuth2 gem uses it to setup some state for testing
it 'should include redirect_uri if full_host is set' do
OmniAuth.config.full_host = 'https://foo.com/'
instance = subject.new('abc', 'def')
instance.authorize_params
instance.token_params[:redirect_uri].should =~ /\Ahttps:\/\/foo\.com/
end
it 'should include redirect_uri if callback_path is set' do
# TODO: It would be nice to grab this from the request URL
# instead of setting it on the config
OmniAuth.config.full_host = 'https://foo.com/'
instance = subject.new('abc', 'def', :callback_path => 'bar/baz')
instance.authorize_params
instance.token_params[:redirect_uri].should == 'https://foo.com/bar/baz'
end
it 'should not include redirect_uri by default' do
instance = subject.new('abc', 'def')
instance.authorize_params
expect(instance.token_params[:redirect_uri]).to be_nil
end
end
describe '#callback_url' do
subject { fresh_strategy }
OmniAuth.config.full_host = 'https://foo.com/'
it 'returns a url with the host and path' do
instance = subject.new('abc', 'def', :callback_path => 'bar/baz')
instance.authorize_params
expect(instance.callback_url).to eq 'https://foo.com/bar/baz'
end
end
end
| ruby | MIT | 468dd9acaccdbba38a38cdbcdf7f10c17be25e89 | 2026-01-04T17:48:51.752026Z | false |
isaacsanders/omniauth-stripe-connect | https://github.com/isaacsanders/omniauth-stripe-connect/blob/468dd9acaccdbba38a38cdbcdf7f10c17be25e89/lib/omniauth-stripe-connect.rb | lib/omniauth-stripe-connect.rb | require "omniauth-stripe-connect/version"
require 'omniauth/stripe_connect'
| ruby | MIT | 468dd9acaccdbba38a38cdbcdf7f10c17be25e89 | 2026-01-04T17:48:51.752026Z | false |
isaacsanders/omniauth-stripe-connect | https://github.com/isaacsanders/omniauth-stripe-connect/blob/468dd9acaccdbba38a38cdbcdf7f10c17be25e89/lib/omniauth-stripe-connect/version.rb | lib/omniauth-stripe-connect/version.rb | module OmniAuth
module StripeConnect
VERSION = "2.10.1"
end
end
| ruby | MIT | 468dd9acaccdbba38a38cdbcdf7f10c17be25e89 | 2026-01-04T17:48:51.752026Z | false |
isaacsanders/omniauth-stripe-connect | https://github.com/isaacsanders/omniauth-stripe-connect/blob/468dd9acaccdbba38a38cdbcdf7f10c17be25e89/lib/omniauth/stripe_connect.rb | lib/omniauth/stripe_connect.rb | require 'omniauth/strategies/stripe_connect'
| ruby | MIT | 468dd9acaccdbba38a38cdbcdf7f10c17be25e89 | 2026-01-04T17:48:51.752026Z | false |
isaacsanders/omniauth-stripe-connect | https://github.com/isaacsanders/omniauth-stripe-connect/blob/468dd9acaccdbba38a38cdbcdf7f10c17be25e89/lib/omniauth/strategies/stripe_connect.rb | lib/omniauth/strategies/stripe_connect.rb | require 'omniauth/strategies/oauth2'
module OmniAuth
module Strategies
class StripeConnect < OmniAuth::Strategies::OAuth2
option :name, :stripe_connect
option :client_options, {
:site => 'https://connect.stripe.com'
}
option :authorize_options, [:scope, :stripe_landing, :always_prompt]
option :provider_ignores_state, true
uid { raw_info[:stripe_user_id] }
info do
{
:name => extra_info[:display_name] || extra_info[:business_name] || extra_info[:email],
:email => extra_info[:email],
:nickname => extra_info[:display_name],
:scope => raw_info[:scope],
:livemode => raw_info[:livemode],
:stripe_publishable_key => raw_info[:stripe_publishable_key]
}
end
extra do
e = {
:raw_info => raw_info
}
e[:extra_info] = extra_info unless skip_info?
e
end
credentials do
hash = {'token' => access_token.token}
hash.merge!('refresh_token' => access_token.refresh_token) if access_token.refresh_token
hash.merge!('expires_at' => access_token.expires_at) if access_token.expires?
hash.merge!('expires' => access_token.expires?)
hash
end
def raw_info
@raw_info ||= deep_symbolize(access_token.params)
end
def extra_info
@extra_info ||= deep_symbolize(access_token.get("https://api.stripe.com/v1/account").parsed)
end
def redirect_params
if options.key?(:callback_path) || OmniAuth.config.full_host
{:redirect_uri => callback_url}
else
{}
end
end
# NOTE: We call redirect_params AFTER super in these methods intentionally
# the OAuth2 strategy uses the authorize_params and token_params methods
# to set up some state for testing that we need in redirect_params
def authorize_params
params = super
params = params.merge(request_params) unless OmniAuth.config.test_mode
redirect_params.merge(params)
end
def token_params
params = super.to_hash(:symbolize_keys => true) \
.merge(:headers => { 'Authorization' => "Bearer #{client.secret}" })
redirect_params.merge(params)
end
def callback_url
full_host + script_name + callback_path
end
def request_phase
redirect client.auth_code.authorize_url(authorize_params)
end
def build_access_token
verifier = request.params['code']
client.auth_code.get_token(verifier, token_params)
end
def request_params
request.params.except(*request_blacklisted_params)
end
def request_blacklisted_params
%w(_method)
end
end
end
end
| ruby | MIT | 468dd9acaccdbba38a38cdbcdf7f10c17be25e89 | 2026-01-04T17:48:51.752026Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/spec/spec_helper.rb | spec/spec_helper.rb | require 'simplecov'
SimpleCov.start
require 'bundler'
Bundler.require :default, :development
require 'completely'
require 'completely/cli'
include Completely
# Consistent Colsole output (for rspec_aprovals)
ENV['TTY'] = 'off'
ENV['COLUMNS'] = '80'
ENV['LINES'] = '30'
# Just in case the developer's environment contains these, we don't need them
ENV['COMPLETELY_DEBUG'] = nil
ENV['COMPLETELY_OUTPUT_PATH'] = nil
ENV['COMPLETELY_CONFIG_PATH'] = nil
def reset_tmp_dir
system 'rm -rf spec/tmp/*'
system 'mkdir -p spec/tmp'
end
RSpec.configure do |config|
config.example_status_persistence_file_path = 'spec/status.txt'
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/spec/completely/completions_spec.rb | spec/completely/completions_spec.rb | describe Completions do
subject { described_class.load path }
let(:path) { "spec/fixtures/#{file}.yaml" }
let(:file) { 'basic' }
describe '::read' do
it 'reads from io' do
io = double :io, read: 'cli: [--help, --version]'
expect(described_class.read(io).config.config).to eq({ 'cli' => %w[--help --version] })
end
end
describe '#valid?' do
context 'when all patterns start with the same word' do
it 'returns true' do
expect(subject).to be_valid
end
end
context 'when not all patterns start with the same word' do
let(:file) { 'broken' }
it 'returns false' do
expect(subject).not_to be_valid
end
end
end
describe '#patterns' do
it 'returns an array of Pattern objects' do
expect(subject.patterns).to be_an Array
expect(subject.patterns.first).to be_a Pattern
end
end
describe '#script' do
it 'returns a bash completions script' do
expect(subject.script).to match_approval 'completions/script'
end
context 'with a configuration file that only includes patterns with spaces' do
let(:file) { 'only-spaces' }
it 'uses the first word of the first command as the function name' do
expect(subject.script).to match_approval 'completions/script-only-spaces'
end
end
context 'when COMPLETELY_DEBUG is set' do
before { ENV['COMPLETELY_DEBUG'] = '1' }
after { ENV['COMPLETELY_DEBUG'] = nil }
it 'adds an additional debug snippet to the script' do
expect(subject.script).to match_approval('completions/script-with-debug')
.except(/case.*/m)
end
end
context 'with a configuration file that includes complete_options' do
let(:file) { 'complete_options' }
it 'adds the complete_options to the complete command' do
expect(subject.script).to match_approval 'completions/script-complete-options'
end
end
end
describe '#wrapper_function' do
it 'returns the script wrapped inside a function' do
expect(subject.wrapper_function).to match_approval 'completions/function'
end
end
describe '#tester' do
it 'returns a Tester object' do
expect(subject.tester).to be_a Tester
end
it 'assigns self.script to tester.script' do
expect(subject.tester.script).to eq subject.script
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/spec/completely/integration_spec.rb | spec/completely/integration_spec.rb | describe 'generated script' do
subject { Completions.load "#{fixture}.yaml" }
let(:response) do
Dir.chdir 'spec/fixtures/integration' do
subject.tester.test(compline).sort
end
end
config = YAML.load_file 'spec/completely/integration.yml'
config.each do |fixture, use_cases|
use_cases.each do |use_case|
describe "#{fixture} ▶ '#{use_case['compline']}'" do
let(:fixture) { fixture }
let(:compline) { use_case['compline'] }
let(:expected) { use_case['expected'] }
it "returns #{use_case['expected'].join ' '}" do
expect(response).to eq expected
end
end
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/spec/completely/zsh_spec.rb | spec/completely/zsh_spec.rb | describe 'zsh compatibility' do
subject do
Dir.chdir 'spec/tmp' do
`#{shell} test.sh`.strip
end
end
let(:completions) { Completely::Completions.load 'spec/fixtures/basic.yaml' }
let(:words) { 'completely generate ' }
let(:tester_script) { completions.tester.tester_script words }
let(:shell) { 'zsh' }
before do
reset_tmp_dir
system 'mkdir -p spec/tmp/somedir'
File.write 'spec/tmp/test.sh', tester_script
end
describe 'completions script and test script' do
it 'returns completions without erroring' do
expect(subject).to eq 'somedir'
end
context 'when running on bash shell' do
let(:shell) { 'bash' }
it 'returns the same output' do
expect(subject).to eq 'somedir'
end
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/spec/completely/bin_spec.rb | spec/completely/bin_spec.rb | describe 'bin/completely' do
subject { CLI.runner }
it 'shows list of commands' do
expect { subject.run }.to output_approval('cli/commands')
end
context 'when an error occurs' do
it 'displays it nicely' do
expect(`bin/completely preview notfound.yaml 2>&1`).to match_approval('cli/error')
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/spec/completely/installer_spec.rb | spec/completely/installer_spec.rb | describe Installer do
subject { described_class.new program: program, script_path: script_path }
let(:leeway) { RUBY_VERSION < '3.2.0' ? 0 : 3 }
let(:program) { 'completely-test' }
let(:script_path) { 'completions.bash' }
let(:targets) { subject.target_directories.map { |dir| "#{dir}/#{program}" } }
let(:install_command) do
%W[sudo cp #{subject.script_path} #{subject.target_path}]
end
let(:uninstall_command) do
%w[sudo rm -f] + targets
end
describe '::from_io' do
subject { described_class.from_io program:, io: }
let(:io) { StringIO.new 'dummy data' }
it 'reads the script from io and writes it to a temp file' do
expect(File.read subject.script_path).to eq 'dummy data'
end
end
describe '::from_string' do
subject { described_class.from_string program:, string: }
let(:string) { 'dummy data' }
it 'reads the script from io and writes it to a temp file' do
expect(File.read subject.script_path).to eq 'dummy data'
end
end
describe '#target_directories' do
it 'returns an array of potential completion directories' do
expect(subject.target_directories).to be_an Array
expect(subject.target_directories.size).to eq 4
end
end
describe '#target_path' do
it 'returns the first matching path' do
expect(subject.target_path)
.to eq '/usr/share/bash-completion/completions/completely-test'
end
end
describe '#install_command' do
it 'returns a copy command as an array' do
expect(subject.install_command)
.to eq %w[sudo cp completions.bash /usr/share/bash-completion/completions/completely-test]
end
context 'when the user is root' do
it 'returns the command without sudo' do
allow(subject).to receive(:root_user?).and_return true
expect(subject.install_command)
.to eq %w[cp completions.bash /usr/share/bash-completion/completions/completely-test]
end
end
end
describe '#install_command_string' do
it 'returns the install command as a string' do
expect(subject.install_command_string).to eq subject.install_command.join(' ')
end
end
describe '#uninstall_command' do
it 'returns an rm command as an array' do
expect(subject.uninstall_command).to eq %w[sudo rm -f] + targets
end
context 'when the user is root' do
it 'returns the command without sudo' do
allow(subject).to receive(:root_user?).and_return true
expect(subject.uninstall_command).to eq %w[rm -f] + targets
end
end
end
describe '#uninstall_command_string' do
it 'returns the uninstall command as a string' do
expect(subject.uninstall_command_string).to eq subject.uninstall_command.join(' ')
end
end
describe '#install' do
let(:existing_file) { 'spec/fixtures/existing-file.txt' }
let(:missing_file) { 'tmp/missing-file' }
before do
allow(subject).to receive_messages(script_path: existing_file, target_path: missing_file)
end
context 'when the completions_path cannot be found' do
it 'raises an error' do
allow(subject).to receive(:completions_path).and_return nil
expect { subject.install }.to raise_approval('installer/install-no-dir')
.diff(leeway)
end
end
context 'when the script cannot be found' do
it 'raises an error' do
allow(subject).to receive(:script_path).and_return missing_file
expect { subject.install }.to raise_approval('installer/install-no-script')
.diff(leeway)
end
end
context 'when the target exists' do
it 'raises an error' do
allow(subject).to receive(:target_path).and_return existing_file
expect { subject.install }.to raise_approval('installer/install-target-exists')
.diff(leeway)
end
end
context 'when the target exists but force=true' do
it 'proceeds to install' do
allow(subject).to receive(:target_path).and_return existing_file
expect(subject).to receive(:system).with(*install_command)
subject.install force: true
end
end
context 'when the target does not exist' do
it 'proceeds to install' do
allow(subject).to receive(:target_path).and_return missing_file
expect(subject).to receive(:system).with(*install_command)
subject.install
end
end
end
describe '#uninstall' do
it 'removes the completions script' do
expect(subject).to receive(:system).with(*uninstall_command)
subject.uninstall
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/spec/completely/config_spec.rb | spec/completely/config_spec.rb | describe Config do
subject { described_class.load path }
let(:path) { "spec/fixtures/#{file}.yaml" }
let(:file) { 'nested' }
let(:config_string) { 'cli: [--help, --version]' }
let(:config_hash) { { 'cli' => %w[--help --version] } }
describe '::parse' do
it 'loads config from string' do
expect(described_class.parse(config_string).config).to eq config_hash
end
context 'when the string is not a valid YAML' do
it 'raises ParseError' do
expect { described_class.parse('not: a: yaml') }.to raise_error(Completely::ParseError)
end
end
end
describe '::read' do
it 'loads config from io' do
io = double :io, read: config_string
expect(described_class.read(io).config).to eq config_hash
end
end
describe '#flat_config' do
it 'returns a flat pattern => completions hash' do
expect(subject.flat_config.to_yaml).to match_approval('config/flat_config')
end
end
context 'when complete_options is defined' do
let(:file) { 'complete_options' }
describe 'config' do
it 'ignores the completely_config YAML key' do
expect(subject.config.keys).to eq ['mygit']
end
end
describe 'options' do
it 'returns the completely_options hash from the YAML file' do
expect(subject.options[:complete_options]).to eq '-o nosort'
end
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/spec/completely/tester_spec.rb | spec/completely/tester_spec.rb | describe Tester do
subject { described_class.new script_path: script_path, function_name: function_name }
let(:function_name) { '_cli_completions' }
let(:script_path) { "spec/fixtures/tester/#{fixture}.bash" }
let(:fixture) { 'default' }
let(:compline) { 'cli co' }
before :all do
# Create an up to date fixture
comps = Completions.load 'spec/fixtures/tester/default.yaml'
File.write 'spec/fixtures/tester/default.bash', comps.script
end
describe '#tester_script' do
it 'sources the script using its absolute path' do
expect(subject.tester_script compline).to match %r{source "/.*spec/fixtures/tester/default.bash"}
end
it 'returns a valid testing script' do
expect(subject.tester_script compline).to match_approval('tester/script_path')
.except(/source "(.*)"/, 'source "<path removed>"')
end
end
describe '#test' do
it 'returns an array with completions' do
expect(subject.test compline).to eq %w[command conquer]
end
end
context 'with script instead of script_path' do
subject { described_class.new script: script, function_name: function_name }
let(:script) { '# some completion script' }
describe '#tester_script' do
it 'includes the embedded script' do
expect(subject.tester_script compline).to match_approval('tester/script')
end
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/spec/completely/pattern_spec.rb | spec/completely/pattern_spec.rb | describe Pattern do
subject { described_class.new text, completions, function_name }
let(:text) { 'git commit' }
let(:completions) { %w[--message --help <file> <user>] }
let(:function_name) { '_filter' }
describe '#length' do
it 'returns the string length of the pattern text' do
expect(subject.length).to eq 10
end
end
describe '#empty?' do
it 'returns false' do
expect(subject).not_to be_empty
end
context 'when there are no completions' do
let(:completions) { nil }
it 'returns true' do
expect(subject).to be_empty
end
end
end
describe '#words' do
it 'returns an array for compgen -W' do
expect(subject.words).to eq %w[--message --help]
end
end
describe '#actions' do
it 'returns an array for compgen -A' do
expect(subject.actions).to eq ['-A file', '-A user']
end
end
describe '#prefix' do
it 'returns the first word of the pattern' do
expect(subject.prefix).to eq 'git'
end
context 'when the pattern includes a * right after the first word' do
let(:text) { 'git*--checkout' }
it 'returns the first word of the pattern' do
expect(subject.prefix).to eq 'git'
end
end
context 'when the pattern includes a * anywhere else' do
let(:text) { 'git --checkout*something' }
it 'returns the first word of the pattern' do
expect(subject.prefix).to eq 'git'
end
end
end
describe '#case_string' do
it 'returns the quoted pattern (excluding command name) with a wildcard suffix' do
expect(subject.case_string).to eq "'commit'*"
end
context 'when the pattern (excluding command name) is empty' do
let(:text) { 'git' }
it "returns '*'" do
expect(subject.case_string).to eq '*'
end
end
context 'when the pattern includes a wildcard' do
let(:text) { 'git checkout*--branch' }
it 'returns the quoted pattern (excluding command name) with an unquoted wildcard, without a wildcard suffix' do
expect(subject.case_string).to eq "'checkout'*'--branch'"
end
end
end
describe '#text_without_prefix' do
it 'returns all but the first word' do
expect(subject.text_without_prefix).to eq 'commit'
end
context 'when the pattern includes a * right after the first word' do
let(:text) { 'git*--checkout' }
it 'returns all but the first word' do
expect(subject.text_without_prefix).to eq '*--checkout'
end
end
context 'when the pattern includes a * anywhere else' do
let(:text) { 'git --checkout*something' }
it 'returns all but the first word' do
expect(subject.text_without_prefix).to eq '--checkout*something'
end
end
end
describe '#compgen' do
it 'returns a line of compgen arguments' do
expect(subject.compgen).to eq '-A file -A user -W "$(_filter "--message --help")"'
end
context 'when there are no words for -W' do
let(:completions) { %w[<file> <user>] }
it 'omits the -W argument' do
expect(subject.compgen).to eq '-A file -A user'
end
end
context 'when there are no actions for -A' do
let(:completions) { %w[--message --help] }
it 'omits the -A arguments' do
expect(subject.compgen).to eq '-W "$(_filter "--message --help")"'
end
end
context 'when there are no completions' do
let(:completions) { nil }
it 'returns nil' do
expect(subject.compgen).to be_nil
end
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/spec/completely/commands/preview_spec.rb | spec/completely/commands/preview_spec.rb | describe Commands::Preview do
subject { described_class.new }
before { system 'cp lib/completely/templates/sample.yaml completely.yaml' }
after { system 'rm -f completely.yaml' }
context 'with --help' do
it 'shows long usage' do
expect { subject.execute %w[preview --help] }.to output_approval('cli/preview/help')
end
end
context 'without arguments' do
it 'outputs the generated script to STDOUT' do
expect { subject.execute %w[preview] }
.to output_approval('cli/generated-script')
end
end
context 'with CONFIG_PATH' do
it 'outputs the generated script to STDOUT' do
expect { subject.execute %w[preview completely.yaml] }
.to output_approval('cli/generated-script')
end
end
context 'with COMPLETELY_CONFIG_PATH env var' do
before do
reset_tmp_dir
system 'cp lib/completely/templates/sample.yaml spec/tmp/hello.yml'
system 'rm -f completely.yaml'
ENV['COMPLETELY_CONFIG_PATH'] = 'spec/tmp/hello.yml'
end
after { ENV['COMPLETELY_CONFIG_PATH'] = nil }
it 'outputs the generated script to STDOUT' do
expect { subject.execute %w[preview] }
.to output_approval('cli/generated-script')
end
end
context 'with an invalid configuration' do
it 'outputs a warning to STDERR' do
expect { subject.execute %w[preview spec/fixtures/broken.yaml] }
.to output_approval('cli/warning').to_stderr
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/spec/completely/commands/install_spec.rb | spec/completely/commands/install_spec.rb | describe Commands::Install do
subject { described_class.new }
let(:leeway) { RUBY_VERSION < '3.2.0' ? 0 : 5 }
let :mock_installer do
instance_double Installer,
install: true,
target_path: 'some-target-path',
install_command_string: 'sudo cp source target'
end
context 'with --help' do
it 'shows long usage' do
expect { subject.execute %w[install --help] }
.to output_approval('cli/install/help')
end
end
context 'without arguments' do
it 'shows short usage' do
expect { subject.execute %w[install] }
.to output_approval('cli/install/no-args')
end
end
context 'with PROGRAM' do
it 'invokes the Installer' do
allow(subject).to receive(:installer).and_return(mock_installer)
expect(mock_installer).to receive(:install)
expect { subject.execute %w[install completely-test] }
.to output_approval('cli/install/install')
end
end
context 'with PROGRAM - (stdin)' do
it 'invokes the Installer using a temp file' do
allow(subject).to receive(:installer).and_return(mock_installer)
allow($stdin).to receive_messages(read: 'dummy data')
expect(mock_installer).to receive(:install)
expect { subject.execute %w[install completely-test -] }
.to output_approval('cli/install/stdin-install')
end
end
context 'with PROGRAM --dry' do
it 'shows the command and does not install anything' do
expect(mock_installer).not_to receive(:install)
expect { subject.execute %w[install completely-test --dry] }
.to output_approval('cli/install/dry')
end
end
context 'with PROGRAM - --dry (stdin)' do
it 'shows the command and does not install anything' do
allow($stdin).to receive_messages(read: 'dummy data')
expect(mock_installer).not_to receive(:install)
expect { subject.execute %w[install completely-test - --dry] }
.to output_approval('cli/install/stdin-dry')
.except(/cp [^\s]*completely-[^\s]*/, 'cp <tmpfile-path>')
end
end
context 'when the installer fails' do
it 'raises an error' do
allow(subject).to receive(:installer).and_return(mock_installer)
allow(mock_installer).to receive(:install).and_return false
expect { subject.execute %w[install completely-test] }
.to raise_approval('cli/install/install-error').diff(leeway)
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/spec/completely/commands/generate_spec.rb | spec/completely/commands/generate_spec.rb | describe Commands::Generate do
subject { described_class.new }
before do
reset_tmp_dir
system 'cp lib/completely/templates/sample.yaml completely.yaml'
end
after do
system 'rm -f completely.yaml'
end
context 'with --help' do
it 'shows long usage' do
expect { subject.execute %w[generate --help] }.to output_approval('cli/generate/help')
end
end
context 'without arguments' do
it 'generates the bash script to completely.bash' do
expect { subject.execute %w[generate] }.to output_approval('cli/generate/no-args')
expect(File.read 'completely.bash').to match_approval('cli/generated-script')
end
it 'generates a shellcheck compliant script' do
expect { subject.execute %w[generate] }.to output_approval('cli/generate/no-args')
expect(`shellcheck completely.bash 2>&1`).to be_empty
end
it 'generates a shfmt compliant script' do
expect { subject.execute %w[generate] }.to output_approval('cli/generate/no-args')
expect(`shfmt -d -i 2 -ci completely.bash 2>&1`).to be_empty
end
end
context 'with CONFIG_PATH' do
it 'generates the bash script to completely.bash' do
expect { subject.execute %w[generate completely.yaml] }.to output_approval('cli/generate/custom-path')
expect(File.read 'completely.bash').to match_approval('cli/generated-script')
end
end
context 'with COMPLETELY_CONFIG_PATH env var' do
before do
reset_tmp_dir
system 'cp lib/completely/templates/sample.yaml spec/tmp/hello.yml'
system 'rm -f completely.yaml'
ENV['COMPLETELY_CONFIG_PATH'] = 'spec/tmp/hello.yml'
end
after do
ENV['COMPLETELY_CONFIG_PATH'] = nil
system 'rm -f hello.bash'
end
it 'generates the bash script to hello.bash' do
expect { subject.execute %w[generate] }.to output_approval('cli/generate/custom-path-env')
expect(File.read 'hello.bash').to match_approval('cli/generated-script')
end
end
context 'with COMPLETELY_OUTPUT_PATH env var' do
let(:outfile) { 'spec/tmp/tada.bash' }
before do
reset_tmp_dir
ENV['COMPLETELY_OUTPUT_PATH'] = outfile
end
after do
ENV['COMPLETELY_OUTPUT_PATH'] = nil
end
it 'generates the bash script to the requested path' do
expect { subject.execute %w[generate] }.to output_approval('cli/generate/custom-path-env2')
expect(File.read outfile).to match_approval('cli/generated-script')
end
end
context 'with CONFIG_PATH OUTPUT_PATH' do
before { reset_tmp_dir }
it 'generates the bash script to the specified path' do
expect { subject.execute %w[generate completely.yaml spec/tmp/out.bash] }
.to output_approval('cli/generate/custom-out-path')
expect(File.read 'spec/tmp/out.bash').to match_approval('cli/generated-script')
end
end
context 'with stdin and stdout' do
it 'reads config from stdin and writes to stdout' do
allow($stdin).to receive_messages(tty?: false, read: File.read('completely.yaml'))
expect { subject.execute %w[generate -] }
.to output_approval('cli/generated-script')
end
end
context 'with stdin and output path' do
let(:outfile) { 'spec/tmp/stdin-to-file.bash' }
it 'reads config from stdin and writes to file' do
allow($stdin).to receive_messages(tty?: false, read: File.read('completely.yaml'))
expect { subject.execute %W[generate - #{outfile}] }.to output_approval('cli/generate/custom-path-stdin')
expect(File.read outfile).to match_approval('cli/generated-script')
end
end
context 'with --function NAME' do
after { system 'rm -f completely.bash' }
it 'uses the provided function name' do
expect { subject.execute %w[generate --function _mycomps] }.to output_approval('cli/generate/function')
expect(File.read 'completely.bash').to match_approval('cli/generated-script-alt')
end
end
context 'with --install PROGRAM' do
let(:mock_installer) do
instance_double Installer,
install: true,
install_command_string: 'stubbed install_command_string',
target_path: 'stubbed target_path'
end
it 'passes the generated script to the installer' do
allow(Installer).to receive(:from_string)
.with(
program: 'mycli',
string: a_string_matching(/bash completions script/)
).and_return(mock_installer)
expect(mock_installer).to receive(:install)
expect { subject.execute %w[generate --install mycli] }.to output_approval('cli/generate/install')
end
end
context 'with --wrap NAME' do
after { system 'rm -f completely.bash' }
it 'wraps the script in a function' do
expect { subject.execute %w[generate --wrap give_comps] }.to output_approval('cli/generate/wrapper')
expect(File.read 'completely.bash').to match_approval('cli/generated-wrapped-script')
end
end
context 'with an invalid configuration' do
it 'outputs a warning to STDERR' do
expect { subject.execute %w[generate spec/fixtures/broken.yaml spec/tmp/out.bash] }
.to output_approval('cli/warning').to_stderr
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/spec/completely/commands/init_spec.rb | spec/completely/commands/init_spec.rb | describe Commands::Init do
subject { described_class.new }
before { system 'rm -f completely.yaml' }
after { system 'rm -f completely.yaml' }
let(:sample) { File.read 'lib/completely/templates/sample.yaml' }
let(:sample_nested) { File.read 'lib/completely/templates/sample-nested.yaml' }
context 'with --help' do
it 'shows long usage' do
expect { subject.execute %w[init --help] }.to output_approval('cli/init/help')
end
end
context 'without arguments' do
it 'creates a new sample file named completely.yaml' do
expect { subject.execute %w[init] }.to output_approval('cli/init/no-args')
expect(File.read 'completely.yaml').to eq sample
end
end
context 'with --nested' do
it 'creates a sample using the nested configuration' do
expect { subject.execute %w[init --nested] }.to output_approval('cli/init/nested')
expect(File.read 'completely.yaml').to eq sample_nested
end
end
context 'with CONFIG_PATH' do
before { reset_tmp_dir }
it 'creates a new sample file with the requested name' do
expect { subject.execute %w[init spec/tmp/in.yaml] }
.to output_approval('cli/init/custom-path')
expect(File.read 'spec/tmp/in.yaml').to eq sample
end
end
context 'with COMPLETELY_CONFIG_PATH env var' do
before do
reset_tmp_dir
ENV['COMPLETELY_CONFIG_PATH'] = 'spec/tmp/hello.yml'
end
after { ENV['COMPLETELY_CONFIG_PATH'] = nil }
it 'creates a new sample file with the requested name' do
expect { subject.execute %w[init] }
.to output_approval('cli/init/custom-path-env')
expect(File.read 'spec/tmp/hello.yml').to eq sample
end
end
context 'when the config file already exists' do
before { system 'cp lib/completely/templates/sample.yaml completely.yaml' }
after { system 'rm -f completely.yaml' }
it 'raises an error' do
expect { subject.execute %w[init] }.to raise_approval('cli/init/file-exists')
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/spec/completely/commands/uninstall_spec.rb | spec/completely/commands/uninstall_spec.rb | describe Commands::Uninstall do
subject { described_class.new }
let(:leeway) { RUBY_VERSION < '3.2.0' ? 0 : 5 }
let :mock_installer do
instance_double Installer,
uninstall: true,
uninstall_command_string: 'rm -f some paths'
end
context 'with --help' do
it 'shows long usage' do
expect { subject.execute %w[uninstall --help] }
.to output_approval('cli/uninstall/help')
end
end
context 'without arguments' do
it 'shows short usage' do
expect { subject.execute %w[uninstall] }
.to output_approval('cli/uninstall/no-args')
end
end
context 'with PROGRAM' do
it 'invokes the Installer' do
allow(subject).to receive(:installer).and_return(mock_installer)
expect(mock_installer).to receive(:uninstall)
expect { subject.execute %w[uninstall completely-test] }
.to output_approval('cli/uninstall/uninstall')
end
end
context 'with PROGRAM --dry' do
it 'shows the command and does not install anything' do
expect(mock_installer).not_to receive(:uninstall)
expect { subject.execute %w[uninstall completely-test --dry] }
.to output_approval('cli/uninstall/dry').diff(20)
end
end
context 'when the installer fails' do
it 'raises an error' do
allow(subject).to receive(:installer).and_return(mock_installer)
allow(mock_installer).to receive(:uninstall).and_return false
expect { subject.execute %w[uninstall completely-test] }
.to raise_approval('cli/uninstall/uninstall-error').diff(leeway)
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/spec/completely/commands/test_spec.rb | spec/completely/commands/test_spec.rb | describe Commands::Test do
subject { described_class.new }
before do
system 'cp lib/completely/templates/sample.yaml completely.yaml'
ENV['COMPLETELY_CONFIG_PATH'] = nil
end
after { system 'rm -f completely.yaml' }
context 'with --help' do
it 'shows long usage' do
expect { subject.execute %w[test --help] }.to output_approval('cli/test/help')
end
end
context 'without arguments' do
it 'shows a short usage' do
expect { subject.execute %w[test] }
.to output_approval('cli/test/usage')
end
end
context 'with COMPLINE' do
it 'prints completions' do
expect { subject.execute ['test', 'mygit --'] }
.to output_approval('cli/test/comps-default')
end
end
context 'with --keep COMPLINE' do
before { system "rm -f #{filename}" }
after { system "rm -f #{filename}" }
let(:filename) { 'completely-tester-1.sh' }
it 'copies the test script to the current directory' do
expect { subject.execute ['test', '--keep', 'mygit status --'] }
.to output_approval('cli/test/comps-default-keep')
expect(File.read filename).to match_approval('cli/test/completely-tester.sh')
end
end
context 'with COMPLINE COMPLINE' do
it 'prints multiple completions' do
expect { subject.execute ['test', 'mygit --', 'mygit s'] }
.to output_approval('cli/test/comps-multi')
end
end
context 'with --keep COMPLINE COMPLINE' do
before { filenames.each { |filename| system "rm -f #{filename}" } }
after { filenames.each { |filename| system "rm -f #{filename}" } }
let(:filenames) { ['completely-tester-1.sh', 'completely-tester-2.sh'] }
it 'copies the test scripts to the current directory' do
expect { subject.execute ['test', '--keep', 'mygit --', 'mygit st'] }
.to output_approval('cli/test/comps-multi-keep')
expect(File.read filenames[0]).to match_approval('cli/test/completely-tester-1.sh')
expect(File.read filenames[1]).to match_approval('cli/test/completely-tester-2.sh')
end
end
context 'when COMPLETELY_CONFIG_PATH is set' do
before do
reset_tmp_dir
File.write 'spec/tmp/in.yaml', { 'play' => %w[command conquer] }.to_yaml
ENV['COMPLETELY_CONFIG_PATH'] = 'spec/tmp/in.yaml'
end
it 'tests against this completely file' do
expect { subject.execute ['test', 'play co'] }
.to output_approval('cli/test/comps-custom-config')
end
end
context 'when there is no completely.yaml or COMPLETELY_CONFIG_PATH' do
before { system 'rm -f completely.yaml' }
it 'fails gracefully' do
expect { subject.execute ['test', 'mygit --'] }
.to raise_approval('cli/test/error')
end
end
context 'with an invalid configuration' do
before do
reset_tmp_dir
File.write 'spec/tmp/in.yaml', { 'one' => %w[anything], 'two' => %w[something] }.to_yaml
ENV['COMPLETELY_CONFIG_PATH'] = 'spec/tmp/in.yaml'
end
it 'outputs a warning to STDERR' do
expect { subject.execute %w[test on] }.to output_approval('cli/warning').to_stderr
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/lib/completely.rb | lib/completely.rb | require 'completely/exceptions'
require 'completely/config'
require 'completely/pattern'
require 'completely/completions'
require 'completely/tester'
require 'completely/installer'
require 'debug' if ENV['COMPLETELY_DEV']
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/lib/completely/version.rb | lib/completely/version.rb | module Completely
VERSION = '0.7.3'
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/lib/completely/exceptions.rb | lib/completely/exceptions.rb | module Completely
class Error < StandardError; end
class InstallError < Error; end
class ParseError < Error; end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/lib/completely/completions.rb | lib/completely/completions.rb | require 'yaml'
require 'erb'
module Completely
class Completions
attr_reader :config
class << self
def load(path, function_name: nil)
new Config.load(path), function_name: function_name
end
def read(io, function_name: nil)
new Config.read(io), function_name: function_name
end
end
def initialize(config, function_name: nil)
@config = config.is_a?(Config) ? config : Config.new(config)
@function_name = function_name
end
def flat_config
@flat_config ||= config.flat_config
end
def patterns
@patterns ||= patterns!
end
def valid?
pattern_prefixes.uniq.one?
end
def script
ERB.new(template, trim_mode: '%-').result(binding)
end
def wrapper_function(name = nil)
name ||= 'send_completions'
script_lines = script.split("\n").map do |line|
clean_line = line.gsub("'") { "\\'" }
" echo $'#{clean_line}'"
end.join("\n")
"#{name}() {\n#{script_lines}\n}"
end
def tester
@tester ||= Tester.new script: script, function_name: function_name
end
private
def patterns!
result = flat_config.map do |text, completions|
Pattern.new text, completions, pattern_function_name
end
result.sort_by { |pattern| -pattern.length }
end
def template_path
@template_path ||= File.expand_path('templates/template.erb', __dir__)
end
def template
@template ||= File.read(template_path)
end
def command
@command ||= flat_config.keys.first.split.first
end
def function_name
@function_name ||= "_#{command}_completions"
end
def pattern_function_name
@pattern_function_name ||= "#{function_name}_filter"
end
def pattern_prefixes
patterns.map(&:prefix)
end
def complete_options_line
options = config.options[:complete_options]
return nil if options.nil? || options.strip.empty?
"#{options} "
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/lib/completely/installer.rb | lib/completely/installer.rb | module Completely
class Installer
class << self
def from_io(program:, io: nil)
io ||= $stdin
raise InstallError, 'io must respond to #read' unless io.respond_to?(:read)
raise InstallError, 'io is closed' if io.respond_to?(:closed?) && io.closed?
from_string program:, string: io.read
end
def from_string(program:, string:)
tempfile = create_tempfile
script_path = tempfile.path
begin
File.write script_path, string
ensure
tempfile.close
end
new program:, script_path:
end
def create_tempfile
tempfile = Tempfile.new ['completely-', '.bash']
tempfiles.push tempfile
tempfile
end
def tempfiles = @tempfiles ||= []
end
attr_reader :program, :script_path
def initialize(program:, script_path: nil)
@program = program
@script_path = script_path
end
def target_directories
@target_directories ||= %W[
/usr/share/bash-completion/completions
/usr/local/etc/bash_completion.d
#{Dir.home}/.local/share/bash-completion/completions
#{Dir.home}/.bash_completion.d
]
end
def install_command
result = root_user? ? [] : %w[sudo]
result + %W[cp #{script_path} #{target_path}]
end
def install_command_string
install_command.join ' '
end
def uninstall_command
result = root_user? ? [] : %w[sudo]
result + %w[rm -f] + target_directories.map { |dir| "#{dir}/#{program}" }
end
def uninstall_command_string
uninstall_command.join ' '
end
def target_path
"#{completions_path}/#{program}"
end
def install(force: false)
unless completions_path
raise InstallError, 'Cannot determine system completions directory'
end
unless script_exist?
raise InstallError, "Cannot find script: m`#{script_path}`"
end
if target_exist? && !force
raise InstallError, "File exists: m`#{target_path}`"
end
system(*install_command)
end
def uninstall
system(*uninstall_command)
end
private
def target_exist?
File.exist? target_path
end
def script_exist?
File.exist? script_path
end
def root_user?
Process.uid.zero?
end
def completions_path
@completions_path ||= begin
result = nil
target_directories.each do |target|
if Dir.exist? target
result = target
break
end
end
result
end
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/lib/completely/cli.rb | lib/completely/cli.rb | require 'mister_bin'
require 'completely/commands/generate'
require 'completely/commands/init'
require 'completely/commands/install'
require 'completely/commands/preview'
require 'completely/commands/test'
require 'completely/commands/uninstall'
require 'completely/version'
module Completely
class CLI
def self.runner
runner = MisterBin::Runner.new version: Completely::VERSION,
header: 'Completely - Bash Completions Generator',
footer: 'Run m`completely COMMAND --help` for more information'
runner.route 'init', to: Commands::Init
runner.route 'preview', to: Commands::Preview
runner.route 'generate', to: Commands::Generate
runner.route 'test', to: Commands::Test
runner.route 'install', to: Commands::Install
runner.route 'uninstall', to: Commands::Uninstall
runner
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/lib/completely/pattern.rb | lib/completely/pattern.rb | module Completely
class Pattern
attr_reader :text, :completions, :function_name
def initialize(text, completions, function_name)
@text = text
@completions = completions || []
@function_name = function_name
end
def length
@length ||= text.size
end
def empty?
completions.empty?
end
def words
@words ||= completions.grep_v(/^<.*>$/)
end
def actions
@actions ||= completions.filter_map do |word|
action = word[/^<(.+)>$/, 1]
"-A #{action}" if action
end
end
def prefix
text.split(/ |\*/).first
end
def case_string
if text_without_prefix.empty?
'*'
elsif text_without_prefix.include? '*'
text_without_prefix.gsub(/([^*]+)/, "'\\1'")
else
"'#{text_without_prefix}'*"
end
end
def text_without_prefix
@text_without_prefix ||= text[/^#{prefix}\s*(.*)/, 1]
end
def compgen
@compgen ||= compgen!
end
private
def compgen!
result = []
result << actions.join(' ').to_s if actions.any?
result << %[-W "$(#{function_name} "#{words.join ' '}")"] if words.any?
result.any? ? result.join(' ') : nil
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/lib/completely/config.rb | lib/completely/config.rb | module Completely
class Config
attr_reader :config, :options
class << self
def parse(str)
new YAML.load(str, aliases: true)
rescue Psych::Exception => e
raise ParseError, "Invalid YAML: #{e.message}"
end
def load(path) = parse(File.read(path))
def read(io) = parse(io.read)
end
def initialize(config)
@options = config.delete('completely_options')&.transform_keys(&:to_sym) || {}
@config = config
end
def flat_config
result = {}
config.each do |root_key, root_list|
result.merge! process_key(root_key, root_list)
end
result
end
private
def process_key(prefix, list)
result = {}
result[prefix] = collect_immediate_children list
result.merge! process_nested_items(prefix, list)
result
end
def collect_immediate_children(list)
list.map do |item|
x = item.is_a?(Hash) ? item.keys.first : item
x.gsub(/^[*+]/, '')
end
end
def process_nested_items(prefix, list)
result = {}
list.each do |item|
next unless item.is_a? Hash
nested_prefix = generate_nested_prefix(prefix, item)
nested_list = item.values.first
result.merge!(process_key(nested_prefix, nested_list))
end
result
end
def generate_nested_prefix(prefix, item)
appended_prefix = item.keys.first.gsub(/^\+/, '*')
appended_prefix = " #{appended_prefix}" unless appended_prefix.start_with? '*'
"#{prefix}#{appended_prefix}"
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/lib/completely/tester.rb | lib/completely/tester.rb | require 'erb'
require 'tempfile'
module Completely
class Tester
attr_reader :script, :script_path, :function_name, :cword, :compline
def initialize(function_name:, script: nil, script_path: nil)
@script = script
@script_path = script_path
@function_name = function_name
end
def test(compline)
Tempfile.create 'completely-tester' do |f|
f << tester_script(compline)
f.flush
`bash #{f.path}`
end.split "\n"
end
def tester_script(compline)
set_compline_vars compline
ERB.new(template, trim_mode: '%-').result(binding)
end
protected
def set_compline_vars(compline)
@compline = compline
@cword = compline.split.size - 1
@cword += 1 if compline.end_with? ' '
end
def absolute_script_path
@absolute_script_path ||= script_path ? File.expand_path(script_path) : nil
end
def template_path
@template_path ||= File.expand_path 'templates/tester-template.erb', __dir__
end
def template
@template ||= File.read template_path
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/lib/completely/commands/test.rb | lib/completely/commands/test.rb | require 'completely/commands/base'
module Completely
module Commands
class Test < Base
summary 'Test completions'
help 'This command can be used to test that your completions script responds with ' \
'the right completions. It works by reading your completely.yaml file, generating ' \
'a completions script, and generating a temporary testing script.'
usage 'completely test [--keep] COMPLINE...'
usage 'completely test (-h|--help)'
option '-k --keep', 'Keep the temporary testing script in the current directory.'
param 'COMPLINE', 'One or more commands to test completions for. ' \
'This will be handled as if a TAB was pressed immediately at the end of it, ' \
'so the last word is considered the active cursor. ' \
'If you wish to complete for the next word instead, end your command with a space.'
environment_config_path
environment_debug
example 'completely test "mygit "'
example 'completely test --keep "mygit status "'
example 'completely test "mygit status --" "mygit init "'
def run
complines.each_with_index do |compline, i|
show_compline compline, filename: "completely-tester-#{i + 1}.sh"
end
syntax_warning unless completions.valid?
end
private
def show_compline(compline, filename: nil)
filename ||= 'completely-tester.sh'
say "b`$` g`#{compline}`<tab>"
puts tester.test(compline).join "\n"
puts
return unless keep
File.write filename, tester_script(compline)
say "Saved m`#{filename}`"
end
def complines
@complines ||= args['COMPLINE']
end
def keep
@keep ||= args['--keep']
end
def completions
@completions ||= Completions.load config_path
end
def tester
@tester ||= completions.tester
end
def tester_script(compline)
tester.tester_script compline
end
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/lib/completely/commands/generate.rb | lib/completely/commands/generate.rb | require 'completely/commands/base'
module Completely
module Commands
class Generate < Base
help 'Generate the bash completion script to file or stdout'
usage 'completely generate [CONFIG_PATH OUTPUT_PATH --function NAME --wrap NAME]'
usage 'completely generate [CONFIG_PATH --install PROGRAM --function NAME]'
usage 'completely generate (-h|--help)'
option_function
option '-w --wrap NAME', 'Wrap the completion script inside a function that echos the ' \
'script. This is useful if you wish to embed it directly in your script.'
option '-i --install PROGRAM', 'Install the generated script as completions for PROGRAM.'
param 'CONFIG_PATH', <<~USAGE
Path to the YAML configuration file [default: completely.yaml].
Use '-' to read from stdin.
Can also be set by an environment variable.
USAGE
param 'OUTPUT_PATH', <<~USAGE
Path to the output bash script.
Use '-' for stdout.
When not provided, the name of the input file will be used with a .bash extension, unless the input is stdin - in this case the default will be to output to stdout.
Can also be set by an environment variable.
USAGE
environment_config_path
environment 'COMPLETELY_OUTPUT_PATH', 'Path to the output bash script.'
environment_debug
def run
wrap = args['--wrap']
output = wrap ? wrapper_function(wrap) : script
if args['--install']
install output
elsif output_path == '-'
show output
else
save output
end
end
private
def install(content)
installer = Installer.from_string program: args['--install'], string: content
success = installer.install force: true
raise InstallError, "Failed running command:\nnb`#{installer.install_command_string}`" unless success
say "Saved m`#{installer.target_path}`"
say 'You may need to restart your session to test it'
end
def show(content) = puts content
def save(content)
File.write output_path, content
say "Saved m`#{output_path}`"
syntax_warning unless completions.valid?
end
def wrapper_function(wrapper_name)
completions.wrapper_function wrapper_name
end
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/lib/completely/commands/uninstall.rb | lib/completely/commands/uninstall.rb | require 'completely/commands/base'
module Completely
module Commands
class Uninstall < Base
summary 'Uninstall a bash completion script'
help <<~HELP
This command will remove the completion script for the specified program from all the bash completion directories.
HELP
usage 'completely uninstall PROGRAM [--dry]'
usage 'completely uninstall (-h|--help)'
option '-d --dry', 'Show the uninstallation command but do not run it'
param 'PROGRAM', 'Name of the program the completions are for.'
def run
if args['--dry']
puts installer.uninstall_command_string
return
end
success = installer.uninstall
raise InstallError, "Failed running command:\nnb`#{installer.uninstall_command_string}`" unless success
say 'Done'
say 'You may need to restart your session to test it'
end
private
def installer
Installer.new program: args['PROGRAM']
end
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/lib/completely/commands/preview.rb | lib/completely/commands/preview.rb | require 'completely/commands/base'
module Completely
module Commands
class Preview < Base
help 'Generate the bash completion script to stdout'
usage 'completely preview [CONFIG_PATH --function NAME]'
usage 'completely preview (-h|--help)'
option_function
param_config_path
environment_config_path
environment_debug
def run
puts script
syntax_warning unless completions.valid?
end
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/lib/completely/commands/base.rb | lib/completely/commands/base.rb | require 'mister_bin'
module Completely
module Commands
class Base < MisterBin::Command
class << self
def param_config_path
param 'CONFIG_PATH', <<~USAGE
Path to the YAML configuration file [default: completely.yaml].
Can also be set by an environment variable.
USAGE
end
def option_function
option '-f --function NAME',
'Modify the name of the function in the generated script.'
end
def environment_config_path
environment 'COMPLETELY_CONFIG_PATH',
'Path to a completely configuration file [default: completely.yaml].'
end
def environment_debug
environment 'COMPLETELY_DEBUG', 'If not empty, the generated script will include ' \
'an additional debugging snippet that outputs the compline and current word to ' \
'a text file when a completion is requested.'
end
end
protected
def script
@script ||= completions.script
end
def completions
@completions ||= if config_path == '-'
raise Error, 'Nothing is piped on stdin' if $stdin.tty?
Completions.read $stdin, function_name: args['--function']
else
Completions.load config_path, function_name: args['--function']
end
end
def config_path
@config_path ||= args['CONFIG_PATH'] || ENV['COMPLETELY_CONFIG_PATH'] || 'completely.yaml'
end
def output_path
@output_path ||= args['OUTPUT_PATH'] || ENV['COMPLETELY_OUTPUT_PATH'] || stdout || "#{config_basename}.bash"
end
def stdout
@stdout ||= config_path == '-' ? '-' : nil
end
def config_basename
File.basename config_path, File.extname(config_path)
end
def syntax_warning
say! "\nr`WARNING:`\nr`Your configuration is invalid.`"
say! 'r`All patterns must start with the same word.`'
end
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/lib/completely/commands/install.rb | lib/completely/commands/install.rb | require 'completely/commands/base'
module Completely
module Commands
class Install < Base
summary 'Install a bash completion script'
help <<~HELP
This command will copy the specified file to one of the bash completion directories.
The target filename will be the program name, and sudo will be used if necessary.
HELP
usage 'completely install PROGRAM [SCRIPT_PATH --force --dry]'
usage 'completely install (-h|--help)'
option '-f --force', 'Overwrite target file if it exists'
option '-d --dry', 'Show the installation command but do not run it'
param 'PROGRAM', 'Name of the program the completions are for.'
param 'SCRIPT_PATH', <<~USAGE
Path to the source bash script [default: completely.bash].
Use '-' to provide the script via stdin.
USAGE
def run
if args['--dry']
puts installer.install_command_string
return
end
success = installer.install force: args['--force']
raise InstallError, "Failed running command:\nnb`#{installer.install_command_string}`" unless success
say "Saved m`#{installer.target_path}`"
say 'You may need to restart your session to test it'
end
def installer
@installer ||= if stdin?
Installer.from_io program:
else
Installer.new program:, script_path: input_script_path
end
end
private
def program = args['PROGRAM']
def stdin? = input_script_path == '-'
def input_script_path = args['SCRIPT_PATH'] || 'completely.bash'
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
bashly-framework/completely | https://github.com/bashly-framework/completely/blob/371d3bc27200bacdb2107d73dba9f719e79a69f2/lib/completely/commands/init.rb | lib/completely/commands/init.rb | require 'completely/commands/base'
module Completely
module Commands
class Init < Base
help 'Create a new sample YAML configuration file'
usage 'completely init [--nested] [CONFIG_PATH]'
usage 'completely init (-h|--help)'
option '-n --nested', 'Generate a nested configuration'
param_config_path
environment_config_path
def run
raise Error, "File already exists: #{config_path}" if File.exist? config_path
File.write config_path, sample
say "Saved m`#{config_path}`"
end
private
def sample
@sample ||= File.read sample_path
end
def nested?
args['--nested']
end
def sample_path
@sample_path ||= begin
sample_name = nested? ? 'sample-nested' : 'sample'
File.expand_path "../templates/#{sample_name}.yaml", __dir__
end
end
end
end
end
| ruby | MIT | 371d3bc27200bacdb2107d73dba9f719e79a69f2 | 2026-01-04T17:48:51.287282Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/app/concerns/time_in_time_zone.rb | app/concerns/time_in_time_zone.rb | module TimeInTimeZone
extend ActiveSupport::Concern
private
def today
time_now.to_date
end
def time_now
Time.now.in_time_zone(time_zone)
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/app/concerns/hash_lookup_helper.rb | app/concerns/hash_lookup_helper.rb | module HashLookupHelper
extend ActiveSupport::Concern
private
def hash_lookup(hash, *keys)
last_value = hash
keys.each do |key|
return unless last_value
last_value = last_value[key]
end
last_value
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/app/helpers/sites_helper.rb | app/helpers/sites_helper.rb | module SitesHelper
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/app/helpers/users_helper.rb | app/helpers/users_helper.rb | module UsersHelper
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/app/helpers/application_helper.rb | app/helpers/application_helper.rb | module ApplicationHelper
def navigation(&block)
content_tag(:nav) do
content_tag(:ul, &block)
end
end
def navigate_to(identifier, body, url, html_options={})
classes = html_options[:class] || []
classes = classes.split(" ") unless classes.is_a?(Array)
classes << "active" if @navigation_id == identifier
classes.uniq!
html_options[:class] = classes.empty? ? nil : classes
content_tag(:li) do
link_to(body, url, html_options)
end
end
def header(heading=nil, &block)
content_for(:header) do
content_tag(:header) do
if block_given? && heading
content_tag(:h1, heading) + content_tag(:span, &block)
elsif block_given?
block.call
elsif heading
content_tag(:h1, heading)
end
end
end
end
def body_id
"#{controller_name}_#{action_name}"
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/app/helpers/pages_helper.rb | app/helpers/pages_helper.rb | module PagesHelper
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/app/helpers/accounts_helper.rb | app/helpers/accounts_helper.rb | module AccountsHelper
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/app/helpers/sensors_helper.rb | app/helpers/sensors_helper.rb | module SensorsHelper
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/app/controllers/sensors_controller.rb | app/controllers/sensors_controller.rb | class SensorsController < ApplicationController
respond_to :html, :except => [:chart]
respond_to :json, :only => [:chart]
navigation :sites
def index
@sensors = site.sensors
respond_with @sensors
end
def show
respond_with sensor
end
def new
@sensor = site.sensors.new
respond_with @sensor
end
def create
if @sensor = site.sensors.create(params[:sensor])
flash.notice = %{"#{@sensor.name}" has been created.}
end
respond_with [site, @sensor]
end
def edit
respond_with sensor
end
def update
if sensor.update_attributes(params[:sensor])
flash.notice = %{"#{sensor.name}" has been updated.}
end
respond_with [site, sensor]
end
def destroy
if sensor.destroy
flash.notice = %{"#{sensor.name}" has been removed.}
end
respond_with [site, sensor]
end
def chart
respond_with sensor.chart_data
end
private
def sensor
@sensor ||= site.sensors.find(params[:id])
end
def site
@site ||= Site.find(params[:site_id])
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/app/controllers/sites_controller.rb | app/controllers/sites_controller.rb | class SitesController < ApplicationController
respond_to :html, :except => [:counters, :chart]
respond_to :json, :only => [:counters, :chart]
navigation :sites
def index
@sites = Site.order(:name)
respond_with @sites
end
def show
respond_with resource
end
def new
respond_with(@site = Site.new)
end
def create
@site = Site.new(params[:site])
if @site.save
flash.notice = %{"#{@site.name}" has been created.}
end
respond_with @site
end
def edit
respond_with resource
end
def update
if resource.update_attributes(params[:site])
flash.notice = %{"#{resource.name}" has been updated.}
end
respond_with resource
end
def destroy
if resource.destroy
flash.notice = %{"#{resource.name}" has been removed.}
end
respond_with resource
end
def counters
respond_with resource.counter_data
end
def chart
respond_with resource.chart_data
end
private
def resource
@site ||= Site.find(params[:id])
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/app/controllers/users_controller.rb | app/controllers/users_controller.rb | class UsersController < ApplicationController
respond_to :html
navigation :users
def index
@users = User.order(:email)
respond_with @users
end
def show
respond_with resource
end
def new
respond_with(@user = User.new)
end
def create
@user = User.new(params[:user])
if @user.save
flash.notice = %{"#{@user.email}" has been added.}
end
respond_with @user, :location => users_path
end
def destroy
resource.destroy
flash.notice = %{"#{@user.email}" has been removed."}
respond_with resource
end
private
def resource
@user ||= User.find(params[:id])
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/app/controllers/pages_controller.rb | app/controllers/pages_controller.rb | class PagesController < ApplicationController
respond_to :html, :except => [:counters, :chart]
respond_to :json, :only => [:counters, :chart]
def show
respond_with page
rescue ActiveRecord::RecordNotFound
render :not_found
end
def find
uri = Snowfinch::Collector.sanitize_uri(params[:page][:uri])
uri_hash = Snowfinch::Collector.hash_uri(uri)
redirect_to site_page_path(site, uri_hash)
end
def counters
respond_with page.counter_data
end
def chart
respond_with page.chart_data
end
private
def page
@page ||= Page.find(site, params[:id])
end
def site
@site ||= Site.find(params[:site_id])
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/app/controllers/application_controller.rb | app/controllers/application_controller.rb | class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :authenticate_user!
private
def user_root_path
sites_path
end
def navigation(identifier)
@navigation_id = identifier
end
def self.navigation(identifier)
before_filter { navigation(identifier) }
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/app/controllers/accounts_controller.rb | app/controllers/accounts_controller.rb | class AccountsController < ApplicationController
respond_to :html
navigation :account
def edit
respond_with user
end
def update
if user.update_with_password(params[:user])
sign_in(user, :bypass => true)
flash.notice = "Your account has been updated."
end
respond_with user, :location => :root
end
private
def user
@user ||= current_user
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/app/models/page.rb | app/models/page.rb | class Page
include TimeInTimeZone
include HashLookupHelper
delegate :time_zone, :to => :site
delegate :[], :to => :@document
def self.find(site, hash, year=Date.today.year)
document = Mongo.db["page_counts"].find_one(:h => hash, :s => site.bson_id)
if document
new(document)
else
raise ActiveRecord::RecordNotFound
end
end
def initialize(document)
@document = document
end
def uri
self["u"]
end
def hash
self["h"]
end
alias_method :to_param, :hash
def site
Site.where(:token => self["s"].to_s).first
end
def counter_data
{
:pageviews_today => pageviews_today,
:active_visitors => active_visitors
}
end
def chart_data
{
:today => chart_pageviews_for_date(today),
:yesterday => chart_pageviews_for_date(today-1)
}
end
private
def chart_pageviews_for_date(date)
month = date.mon.to_s
day = date.day.to_s
page = Mongo.db["page_counts"].find_one(
{ "s" => site.bson_id, "y" => date.year, "u" => uri },
{ :fields => ["#{month}.#{day}"] }
)
hours = date == today ? time_now.hour + 1 : 24
hours.times.map do |hour|
count = hash_lookup(page, month, day, hour.to_s, "c") || 0
[hour, count]
end
end
def pageviews_today
month = today.mon.to_s
day = today.day.to_s
page = Mongo.db["page_counts"].find_one(
{ "s" => site.bson_id, "y" => today.year, "u" => uri },
{ :fields => ["#{month}.#{day}.c"] }
)
hash_lookup(page, month, day, "c") || 0
end
def active_visitors
min_heartbeat = Time.now.to_i - 15 * 60
spec = {
"s" => site.bson_id,
"h" => { :$gt => min_heartbeat },
"p" => hash
}
Mongo.db["visits"].find(spec).count
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/app/models/sensor_host.rb | app/models/sensor_host.rb | class SensorHost < ActiveRecord::Base
belongs_to :sensor
validates_presence_of :host
validates_uniqueness_of :host, :scope => :sensor_id
after_save :sync_with_mongodb
private
def sync_with_mongodb
sensor.send(:sync_with_mongodb)
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/app/models/sensor.rb | app/models/sensor.rb | class Sensor < ActiveRecord::Base
include TimeInTimeZone
include HashLookupHelper
has_many :hosts, :class_name => "SensorHost"
belongs_to :site
accepts_nested_attributes_for :hosts,
:allow_destroy => true,
:reject_if => proc { |attributes| attributes["host"].strip.empty? }
validates_associated :hosts
validates_presence_of :name, :site, :type
validates_presence_of :uri_query_key, :uri_query_value, :if => :query_based?
after_save :sync_with_mongodb
after_destroy :sync_with_mongodb
self.inheritance_column = nil
delegate :time_zone, :to => :site
alias_method :hosts_attributes_with_duplicates=, :hosts_attributes=
def hosts_attributes=(attributes)
attributes.each do |key, attr|
attributes.delete(key) if attributes.select { |k,v| v == attr }.count > 1
end
self.hosts_attributes_with_duplicates = attributes
end
def chart_data
{
:today => chart_entries_for_date(today),
:yesterday => chart_entries_for_date(today-1)
}
end
private
def sync_with_mongodb
sensors = site.sensors.all.map do |sensor|
case sensor.type
when "query"
{
"id" => sensor.id,
"type" => "query",
"key" => sensor.uri_query_key,
"value" => sensor.uri_query_value
}
when "referrer"
{
"id" => sensor.id,
"type" => "referrer",
"hosts" => sensor.hosts.all.map(&:host)
}
end
end
Mongo.db["sites"].update(
{ :_id => site.bson_id },
{ :$set => { "sensors" => sensors } }
)
end
def query_based?
type == "query"
end
def chart_entries_for_date(date)
month = date.mon.to_s
day = date.day.to_s
sensor = Mongo.db["sensor_counts"].find_one(
{ "s" => site.bson_id, "y" => date.year, "id" => id },
{ :fields => ["#{month}.#{day}"] }
)
hours = date == today ? time_now.hour + 1 : 24
hours.times.map do |hour|
count = hash_lookup(sensor, month, day, hour.to_s, "c") || 0
[hour, count]
end
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/app/models/site.rb | app/models/site.rb | class Site < ActiveRecord::Base
include TimeInTimeZone
include HashLookupHelper
has_many :sensors, :dependent => :destroy
validates_presence_of :name, :time_zone
before_create :create_mongo_site
after_rollback :remove_mongo_site
after_destroy :remove_mongo_site
def time_zone_id
ActiveSupport::TimeZone::MAPPING[time_zone]
end
def counter_data
{
:pageviews_today => pageviews_today,
:active_visitors => active_visitors,
:visitors_today => visitors_today
}
end
def chart_data
{
:today => chart_pageviews_for_date(today),
:yesterday => chart_pageviews_for_date(today-1)
}
end
def bson_id
BSON::ObjectId(token)
end
def tracked?
Mongo.db["site_counts"].find("s" => bson_id).any?
end
private
def create_mongo_site
self.token = Mongo.db["sites"].insert({ :tz => time_zone_id }).to_s
end
def remove_mongo_site
Mongo.db["sites"].remove("_id" => bson_id)
end
def chart_pageviews_for_date(date)
month = date.mon.to_s
day = date.day.to_s
site = Mongo.db["site_counts"].find_one(
{ "s" => bson_id, "y" => date.year },
{ :fields => ["#{month}.#{day}"] }
)
hours = date == today ? time_now.hour + 1 : 24
hours.times.map do |hour|
count = hash_lookup(site, month, day, hour.to_s, "c") || 0
[hour, count]
end
end
def pageviews_today
month = today.mon.to_s
day = today.day.to_s
site = Mongo.db["site_counts"].find_one(
{ "s" => bson_id, "y" => today.year },
{ :fields => ["#{month}.#{day}.c"] }
)
hash_lookup(site, month, day, "c") || 0
end
def active_visitors
min_heartbeat = Time.now.to_i - 15 * 60
spec = { "s" => bson_id, "h" => { :$gt => min_heartbeat } }
Mongo.db["visits"].find(spec).count
end
def visitors_today
Mongo.db["visitors"].find("s" => bson_id, "d" => today.to_s).count
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/app/models/user.rb | app/models/user.rb | class User < ActiveRecord::Base
devise :database_authenticatable, :lockable, :recoverable, :rememberable,
:trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me
before_validation :generate_password_if_unset, :on => :create
after_create :send_account_information_email
private
def generate_password_if_unset
self.password ||= SecureRandom.hex(6)
end
def send_account_information_email
UserMailer.account_information(self).deliver
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/app/mailers/user_mailer.rb | app/mailers/user_mailer.rb | class UserMailer < ActionMailer::Base
default :from => Snowfinch.configuration[:mailer_sender]
def account_information(user)
@user = user
@host = Snowfinch.configuration[:host]
mail :to => @user.email, :subject => "Account for #{@host}"
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/db/seeds.rb | db/seeds.rb | User.create! :email => "user@snowfinch.net", :password => "snowfinch"
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/db/schema.rb | db/schema.rb | # 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 to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20110410155204) do
create_table "sensor_hosts", :force => true do |t|
t.string "host"
t.integer "sensor_id"
end
add_index "sensor_hosts", ["sensor_id"], :name => "index_sensor_hosts_on_sensor_id"
create_table "sensors", :force => true do |t|
t.string "name"
t.integer "site_id"
t.datetime "created_at"
t.datetime "updated_at"
t.string "type"
t.string "uri_query_key"
t.string "uri_query_value"
end
add_index "sensors", ["site_id"], :name => "index_sensors_on_site_id"
create_table "sites", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
t.string "token"
t.string "time_zone"
end
create_table "users", :force => true do |t|
t.string "email", :default => "", :null => false
t.string "encrypted_password", :limit => 128, :default => "", :null => false
t.string "reset_password_token"
t.string "remember_token"
t.datetime "remember_created_at"
t.integer "sign_in_count", :default => 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.integer "failed_attempts", :default => 0
t.string "unlock_token"
t.datetime "locked_at"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "users", ["email"], :name => "index_users_on_email", :unique => true
add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true
add_index "users", ["unlock_token"], :name => "index_users_on_unlock_token", :unique => true
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/db/migrate/20110410155204_remove_password_salt_from_users.rb | db/migrate/20110410155204_remove_password_salt_from_users.rb | class RemovePasswordSaltFromUsers < ActiveRecord::Migration
def self.up
remove_column :users, :password_salt
end
def self.down
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/db/migrate/20110216145846_devise_create_users.rb | db/migrate/20110216145846_devise_create_users.rb | class DeviseCreateUsers < ActiveRecord::Migration
def self.up
create_table(:users) do |t|
t.database_authenticatable :null => false
t.recoverable
t.rememberable
t.trackable
t.lockable :lock_strategy => :failed_attempts, :unlock_strategy => :both
t.encryptable
t.timestamps
end
add_index :users, :email, :unique => true
add_index :users, :reset_password_token, :unique => true
add_index :users, :unlock_token, :unique => true
end
def self.down
drop_table :users
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/db/migrate/20110316161329_add_type_and_query_fields_to_sensors.rb | db/migrate/20110316161329_add_type_and_query_fields_to_sensors.rb | class AddTypeAndQueryFieldsToSensors < ActiveRecord::Migration
def self.up
add_column :sensors, :type, :string
add_column :sensors, :uri_query_key, :string
add_column :sensors, :uri_query_value, :string
end
def self.down
remove_column :sensors, :uri_query_value
remove_column :sensors, :uri_query_key
remove_column :sensors, :type
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/db/migrate/20110303181824_add_time_zone_to_sites.rb | db/migrate/20110303181824_add_time_zone_to_sites.rb | class AddTimeZoneToSites < ActiveRecord::Migration
def self.up
add_column :sites, :time_zone, :string
end
def self.down
remove_column :sites, :time_zone
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/db/migrate/20110228121355_add_token_to_sites.rb | db/migrate/20110228121355_add_token_to_sites.rb | class AddTokenToSites < ActiveRecord::Migration
def self.up
add_column :sites, :token, :string
end
def self.down
remove_column :sites, :token
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/db/migrate/20110311114859_create_sensors.rb | db/migrate/20110311114859_create_sensors.rb | class CreateSensors < ActiveRecord::Migration
def self.up
create_table :sensors do |t|
t.string :name
t.integer :site_id
t.timestamps
end
add_index :sensors, :site_id
end
def self.down
drop_table :sensors
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/db/migrate/20110316184425_create_sensor_hosts.rb | db/migrate/20110316184425_create_sensor_hosts.rb | class CreateSensorHosts < ActiveRecord::Migration
def self.up
create_table :sensor_hosts do |t|
t.string :host
t.integer :sensor_id
end
add_index :sensor_hosts, :sensor_id
end
def self.down
drop_table :sensor_hosts
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/db/migrate/20110219100357_create_sites.rb | db/migrate/20110219100357_create_sites.rb | class CreateSites < ActiveRecord::Migration
def self.up
create_table :sites do |t|
t.string :name
t.timestamps
end
end
def self.down
drop_table :sites
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/autotest/discover.rb | autotest/discover.rb | require "autotest/growl"
Autotest.add_discovery { "rails" }
Autotest.add_discovery { "rspec2" }
Autotest.add_hook :initialize do |at|
at.add_mapping(/^spec\/acceptance\/.*_spec.rb$/) { |f| f }
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/spec/factories.rb | spec/factories.rb | FactoryGirl.define do
sequence :email do |i|
"user-#{i}@snowfinch.net"
end
factory :user do
email
password "123456"
end
factory :site do
name "Snowfinch"
time_zone "Helsinki"
end
factory :sensor do
name "Social Media"
type "host"
site
end
factory :sensor_host do
host "google.com"
sensor
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/spec/spec_helper.rb | spec/spec_helper.rb | require "simplecov"
SimpleCov.start do
add_filter "config/initializers"
add_filter "spec/acceptance/support"
end
ENV["RAILS_ENV"] ||= "test"
require File.expand_path("../../config/environment", __FILE__)
require "rspec/rails"
require "shoulda-matchers"
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.mock_with :rspec
config.use_transactional_fixtures = false
config.include EmailSpec::Helpers
config.include EmailSpec::Matchers
config.before(:suite) do
DatabaseCleaner.strategy = :truncation
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
Capybara.reset_sessions!
DatabaseCleaner.start
Capybara.current_driver = :selenium if example.metadata[:js]
Mongo.db.collections.each do |collection|
collection.drop unless collection.name =~ /^system\./
end
end
config.after(:each) do
Timecop.return
DatabaseCleaner.clean
Capybara.use_default_driver if example.metadata[:js]
end
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
jcxplorer/snowfinch | https://github.com/jcxplorer/snowfinch/blob/ffe6032de2adce64d3bea78cce401e7c9f75b701/spec/helpers/accounts_helper_spec.rb | spec/helpers/accounts_helper_spec.rb | require 'spec_helper'
describe AccountsHelper do
end
| ruby | MIT | ffe6032de2adce64d3bea78cce401e7c9f75b701 | 2026-01-04T17:48:47.586566Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.