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
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/lib/callback_hell/reports/callbacks/line.rb
lib/callback_hell/reports/callbacks/line.rb
# frozen_string_literal: true module CallbackHell module Reports module Callbacks class Line < LineBase private def report_title "Callback Hell callbacks report:" end def format_callback_name(callback) "#{callback.kind}_#{callback.callback_group}" end end end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/lib/callback_hell/reports/callbacks/github.rb
lib/callback_hell/reports/callbacks/github.rb
# frozen_string_literal: true module CallbackHell module Reports module Callbacks class Github < GithubBase private def report_title "Callback Hell callbacks report" end def format_group_name(callback) "#{timing_symbol(callback.kind)}/#{callback.callback_group}" end def timing_symbol(timing) case timing when :before, "before" then "⇥" when :after, "after" then "↦" when :around, "around" then "↔" else " " end end end end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/lib/callback_hell/reports/validations/table.rb
lib/callback_hell/reports/validations/table.rb
# frozen_string_literal: true module CallbackHell module Reports module Validations class Table < TableBase private def report_title "Callback Hell validations report" end def format_group_name(callback) callback.validation_type end end end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/lib/callback_hell/reports/validations/line.rb
lib/callback_hell/reports/validations/line.rb
# frozen_string_literal: true module CallbackHell module Reports module Validations class Line < LineBase private def report_title "Callback Hell validations report:" end def format_callback_name(callback) if callback.method_name.is_a?(Symbol) || callback.method_name.is_a?(String) type = callback.validation_type (type == "custom") ? "custom (#{callback.method_name})" : type else callback.validation_type end end end end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/lib/callback_hell/reports/validations/github.rb
lib/callback_hell/reports/validations/github.rb
# frozen_string_literal: true module CallbackHell module Reports module Validations class Github < GithubBase private def report_title "Callback Hell validations report" end def format_group_name(callback) callback.validation_type end end end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/ext/qml/extconf.rb
ext/qml/extconf.rb
require 'mkmf' require 'pathname' require '../../lib/qml/platform' # find qmake qmake = with_config('qmake') || find_executable('qmake') debug_enabled = enable_config('debug') clean_enabled = enable_config('clean') qmake_opts = debug_enabled ? 'CONFIG+=debug' : '' # build libqmlbind qmlbind_dir = Pathname.pwd + 'lib/libqmlbind/qmlbind' Dir.chdir(qmlbind_dir) do puts " >>> building libqmlbind..." system "#{qmake} #{qmake_opts}" system "make clean" if clean_enabled system "make -j4" or abort "ERROR: Failed to build libqmlbind" end case when QML::Platform.mac? lib_path = qmlbind_dir + 'libqmlbind.dylib' system "install_name_tool -id #{lib_path} #{lib_path}" when QML::Platform.windows? # TODO else $LDFLAGS << " -Wl,-rpath #{qmlbind_dir}" end # build plugin Dir.chdir "rubyqml-plugin" do puts " >>> building rubyqml-plugin..." system "#{qmake} #{qmake_opts}" system "make clean" if clean_enabled system "make -j4" or abort "ERROR: Failed to build plugin" end puts " >>> configuring..." # create makefile $LDFLAGS << " -L#{qmlbind_dir} -lqmlbind" $CPPFLAGS << " -I#{qmlbind_dir + 'include'}" $CPPFLAGS << " -g" if debug_enabled $CFLAGS << " -std=c99" $CXXFLAGS << " -std=c++11" # create makefile create_makefile 'qml/qml'
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/spec/qml_spec.rb
spec/qml_spec.rb
require 'spec_helper' describe QML do it 'should have a version number' do expect(QML::VERSION).not_to be_nil end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/spec/spec_helper.rb
spec/spec_helper.rb
require 'coveralls' Coveralls.wear! $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'qml' Dir.glob(Pathname(__FILE__) +'../shared/**/*.rb') do |f| require f end QML.init(%w{-platform offscreen})
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/spec/qml/reactive_spec.rb
spec/qml/reactive_spec.rb
require 'spec_helper' describe QML::Reactive do let(:button_class) do Class.new do include QML::Reactive signal :pressed property(:is_pressed) { false } property :id property(:is_id_changed) { false } on :pressed do |pos| self.is_pressed = true end on_changed :id do self.is_id_changed = true end end end let(:button) { button_class.new } describe '.on' do it 'registers a signal listener' do expect(button.is_pressed).to eq(false) button.pressed.emit expect(button.is_pressed).to eq(true) end end describe '.on_changed' do it 'registers a property change listener' do expect(button.is_id_changed).to eq(false) button.id = "foo" expect(button.is_id_changed).to eq(true) end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/spec/qml/js_function_spec.rb
spec/qml/js_function_spec.rb
require 'spec_helper' describe QML::JSFunction do let(:function) do QML.engine.evaluate <<-JS (function(a, b) { return a + b; }); JS end let(:constructor) do QML.engine.evaluate <<-JS (function(a, b) { this.value = a + b; }); JS end describe '#call' do it 'calls function' do expect(function.call(1,2)).to eq 3 end end describe '#new' do it 'calls function as a constructor' do expect(constructor.new(1, 2).value).to eq 3 end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/spec/qml/js_object_spec.rb
spec/qml/js_object_spec.rb
require 'spec_helper' describe QML::JSObject do let(:obj_script) do <<-JS ({one: 1, two: 2}) JS end let(:obj) { QML.engine.evaluate(obj_script) } describe '#[]' do it 'get property' do expect(obj['one']).to eq(1) expect(obj['two']).to eq(2) end end describe '#each' do it 'enumerates each item' do expect(obj.each.to_a).to eq [["one", 1], ["two", 2]] end end describe '#each_pair' do it 'enumerates each item' do expect(obj.each_pair.to_a).to eq [["one", 1], ["two", 2]] end end describe '#to_hash' do it 'converts it to a Hash' do expect(obj.to_hash).to eq({"one" => 1, "two" => 2}) end end describe '#keys' do it 'returns all keys' do expect(obj.keys).to eq %w{one two} end end describe '#values' do it 'returns all values' do expect(obj.values).to eq [1, 2] end end describe '#has_key?' do it 'returns whether it has the key' do expect(obj.has_key?(:one)).to eq true expect(obj.has_key?(:hoge)).to eq false end end describe '#respond_to?' do it 'returns whether it has the key method' do expect(obj.respond_to?(:one)).to eq true expect(obj.respond_to?(:hoge)).to eq false expect(obj.respond_to?(:respond_to?)).to eq true end end describe '#==' do let(:obj_script) do <<-JS ({ obj: {} }) JS end it 'returns identity' do expect(obj.obj).to eq(obj.obj) end end describe 'method call' do let(:obj_script) do <<-JS ({ one: 1, addOne: function(x) { return x + this.one; } }) JS end context 'for non-function property' do it 'get it' do expect(obj.one).to eq 1 end end context 'for function' do it 'call it as method' do expect(obj.addOne(2)).to eq 3 end end context 'for non-existing key' do it 'fails with NoMethodError' do expect { obj.hoge }.to raise_error(NoMethodError) end end context 'as setter' do it 'assigns value' do obj.one = 2 expect(obj.one).to eq 2 end end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/spec/qml/interface_spec.rb
spec/qml/interface_spec.rb
require 'spec_helper' describe QML::Interface do describe '.notify_error' do let(:error) do begin fail "hoge" rescue => e e end end it 'prints an error to stderr' do expect { QML::Interface.notify_error(error) } .to output(/#{error.message}/).to_stderr end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/spec/qml/qt_spec.rb
spec/qml/qt_spec.rb
require 'spec_helper' describe QML do describe '.qt' do it 'returns the Qt object' do expect(QML.qt.md5('hoge')).to eq('ea703e7aa1efda0064eaa507d9e8ab7e') end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/spec/qml/to_qml_spec.rb
spec/qml/to_qml_spec.rb
require 'spec_helper' describe '#to_qml' do let(:through) { QML.engine.evaluate("(function(x) { return x; })") } primitives = { Fixnum: 10, Float: 1.5, Rational: 5/2r, TrueClass: true, FalseClass: false, String: 'ほげ' } primitives.each do |type, value| describe "#{type}\#to_qml" do it "converts #{type} to JS correspondings" do expect(through.call(value)).to eq value end end end describe 'Symbol#to_qml' do it 'converts Symbol to JS string' do expect(through.call(:hoge)).to eq 'hoge' end end describe 'Hash#to_qml' do it 'converts hash to JS object' do hash = {a: 1, b: 2} obj = through.call(hash); expect(obj).to be_a QML::JSObject hash.each do |k, v| expect(obj[k]).to eq v end end end describe 'Array#to_qml' do it 'converts array to JS array' do array = [1,2,3] jsarray = through.call(array) expect(jsarray).to be_a QML::JSArray expect(jsarray.each.to_a).to eq array end end describe 'Time#to_qml' do it 'converts time to JS Date' do time = Time.now # millisecond precision time -= (time.nsec % 1000000) / 1000000000r jsarray = through.call(time) expect(jsarray.to_time).to eq time end end describe 'Access#to_qml' do it 'converts access to QML value' do access = AccessExample.new obj = through.call(access) expect(obj.some_method(1, 2)).to eq(3) end end describe 'Proc#to_qml' do it 'converts Proc into JS function' do proc = -> (hoge) { hoge * 2 } func = through.call(proc) expect(func).to be_a(QML::JSFunction) expect(func.call(2)).to eq(4) end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/spec/qml/signal_connect_spec.rb
spec/qml/signal_connect_spec.rb
require 'spec_helper' describe "QML signal connection" do let(:component) do QML::Component.new(data: <<-QML) import QtQuick 2.0 QtObject { signal someSignal(var arg) } QML end let(:obj) { component.create } it "connects QML signals to ruby proc" do received_arg = nil obj[:someSignal].connect do |arg| received_arg = arg end obj.someSignal(10) expect(received_arg).to eq(10) end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/spec/qml/signal_spec.rb
spec/qml/signal_spec.rb
require 'spec_helper' describe QML::Signal do before do @signal = QML::Signal.new([:foo, :bar]) end describe 'connection' do describe '#connect, #emit' do before do @signal.connect { |foo, bar| @received = [foo, bar] } end it 'connects a block and calls it' do @signal.emit('apple', 'orange') expect(@received).to eq(['apple', 'orange']) end context 'when the number of arguments is wrong' do it 'fails with an ArgumentError' do expect { @signal.emit('apple') }.to raise_error(ArgumentError) end end it 'calls connected blocks in the order they have been conncted' do received = [] @signal.connect { received << 'first' } @signal.connect { received << 'second' } @signal.emit('foo', 'bar') expect(received).to eq(['first', 'second']) end end describe '::Connection#disconnect' do it 'disconnects the connection' do connection = @signal.connect { |foo, bar| @received = foo + bar } @signal.emit('apple', 'orange') connection.disconnect @signal.emit('banana', 'grape') expect(@received).to eq('appleorange') end end describe '#connection_count' do it 'returns the number of connections' do prc1 = ->(foo, bar) {} prc2 = ->(foo, bar) {} @signal.connect(&prc1) @signal.connect(&prc2) expect(@signal.connection_count).to eq(2) end end end describe 'attributes' do describe '#arity' do it 'returns the number of arguments' do expect(@signal.arity).to eq(2) end end describe '#parameters' do it 'returns the parameter information' do expect(@signal.parameters).to eq([[:req, :foo], [:req, :bar]]) end end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/spec/qml/application_spec.rb
spec/qml/application_spec.rb
require 'spec_helper' describe QML::Application do let(:application) { QML.application } describe '#engine' do it 'returns the default engine of the application' do expect(application.engine).to be_a(QML::Engine) end end describe '#load_data' do let(:data) do <<-EOS import QtQuick 2.0 QtObject { property string name: 'foo' } EOS end it 'loads root object 1from data' do application.load_data data expect(application.root_component.data).to eq data expect(application.root.name).to eq 'foo' end end describe '#load_path' do let(:path) { QML::ROOT_PATH + 'spec/assets/testobj.qml' } it 'loads root object from path' do application.load_path path expect(application.root_component.path).to eq path expect(application.root.name).to eq 'foo' end end end describe QML do describe '.application' do it 'returns the QML::Application instance' do expect(QML.application).to be_a(QML::Application) end end describe '.next_tick' do it 'do a task later in event loop' do finished = false QML.next_tick do finished = true end QML.application.process_events expect(finished).to eq true end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/spec/qml/access_spec.rb
spec/qml/access_spec.rb
require 'spec_helper' describe QML::Access do let(:component) { QML::Component.new data: data } let(:root) { component.create } describe '.register_to_qml' do context 'when namespace, version, name are given' do let(:data) do <<-EOS import QtQuick 2.2 import AccessExampleNS 1.2 Item { id: root property var bound: example.text + example.text function getExample() { return example; } function callSomeMethod() { return example.some_method(100, 200); } AccessExample { id: example property var signalArg onSome_signal: { signalArg = arg; } } } EOS end let(:example) { root.getExample } it 'registers the class as a QML type' do expect { component.create }.not_to raise_error end describe 'AccessExamle#some_method' do it 'returns value' do expect(root.callSomeMethod()).to eq 300 end end describe 'AccessExamle text property' do it 'can be used to property binding' do example.text = "foo" expect(root.bound).to eq 'foofoo' example.text = "bar" expect(root.bound).to eq 'barbar' end end describe 'AccessExamle some_signal signal' do it 'can be connected' do example.unwrap.some_signal.emit('foo') expect(example.signalArg).to eq 'foo' end end end context 'when arguments are omitted' do let(:data) do <<-EOS import AccessExampleModule 0.1 AccessExample {} EOS end it 'guesses them from the Ruby class name, namespace and VERSION constant' do expect { component.create }.not_to raise_error end end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/spec/qml/plugin_loader_spec.rb
spec/qml/plugin_loader_spec.rb
require 'spec_helper' describe QML::PluginLoader do let(:loader) { QML::PluginLoader.new path, 'rubyqml-plugin' } describe '#instance' do context 'with signle path' do let(:path) { QML::ROOT_PATH + 'ext/qml/rubyqml-plugin' + QML::PluginLoader.lib_filename('rubyqml-plugin') } let(:loader) { QML::PluginLoader.new path } it 'returns an object instance' do expect(loader.instance).to respond_to('createListModel') end end context 'with correct file path' do let(:path) { QML::ROOT_PATH + 'ext/qml/rubyqml-plugin' } it 'returns an object instance' do expect(loader.instance).to respond_to('createListModel') end end context 'with wrong file path' do let(:path) { QML::ROOT_PATH + 'ext/qml/plugins/wrong' } it 'fails with QML::PluginError' do expect { loader.instance }.to raise_error(QML::PluginError) end end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/spec/qml/engine_spec.rb
spec/qml/engine_spec.rb
require 'spec_helper' describe QML::Engine do describe '#add_import_path' do context 'with test module' do let(:path) { QML::ROOT_PATH + 'spec/assets' } before do QML.engine.add_import_path(path) end let(:data) do <<-EOS import QtQuick 2.0 import testmodule 1.0 Test {} EOS end let(:component) { QML::Component.new(data: data) } it 'loads a module' do expect(component.create.name).to eq 'poyo' end end end describe '#evaluate' do it 'evaluates JS scripts' do result = QML.engine.evaluate <<-JS (function() { return "foo"; })(); JS expect(result).to eq('foo') end context 'with error' do it 'fails with QMLError' do block = proc do QML.engine.evaluate <<-JS (function() { throw new Error("hoge"); })(); JS end expect(&block).to raise_error(/hoge/) end end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/spec/qml/component_spec.rb
spec/qml/component_spec.rb
require 'spec_helper' describe QML::Component do describe '#create' do context 'with string' do let(:data) do <<-EOS import QtQuick 2.0 QtObject { property string name: 'foo' } EOS end let(:component) { QML::Component.new(data: data) } it 'instantiates a object' do expect(component.create.name).to eq 'foo' end describe '#data' do it 'returns its data' do expect(component.data).to eq data end end end context 'with file path' do let(:path) { QML::ROOT_PATH + 'spec/assets/testobj.qml' } let(:component) { QML::Component.new(path: path) } it 'instantiates a object' do expect(component.create.name).to eq 'foo' end describe '#path' do it 'returns its path' do expect(component.path).to eq path end end end end describe '#initialize' do context 'when neither string nor path specified' do it 'fails with TypeError' do expect { QML::Component.new }.to raise_error(TypeError) end end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/spec/qml/js_array_spec.rb
spec/qml/js_array_spec.rb
require 'spec_helper' describe QML::JSArray do let(:array_script) do <<-JS [1, 2, 3] JS end let(:array) { QML.engine.evaluate(array_script) } describe '#each' do it 'enumerates each values' do expect(array.each.to_a).to eq [1,2,3] end end describe '#to_a' do it 'converts it to an array' do expect(array.to_a).to eq [1,2,3] end end describe '#length' do it 'returns length' do expect(array.length).to eq 3 end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/spec/qml/data/array_model_spec.rb
spec/qml/data/array_model_spec.rb
require 'spec_helper' describe QML::ArrayModel do class TestArrayModel < QML::ArrayModel def initialize super(:title, :number) end end let(:original_array) do [ {title: 'hoge', number: 12}, {title: 'piyo', number: 34}, {title: 'fuga', number: 1234} ] end let(:additional_array) do [ {title: 'foo', number: 56}, {title: 'bar', number: 78} ] end let(:expected_array) { original_array.dup } let(:model) do TestArrayModel.new.tap do |model| model.push(*original_array) end end include_context 'ListView for model available' shared_examples 'same as expected array' do |text| it text do expect(model.to_a).to eq(expected_array) end end describe '#each' do context 'with no block' do it 'returns an Enumerator' do expect(model.each).to be_a Enumerator expect(model.each.to_a).to eq expected_array end end context 'with block' do it 'iterates each item' do items = [] model.each do |item| items << item end expect(items).to eq expected_array end end end describe '#to_a' do it 'returns the array the elements are stored in' do expect(model.to_a).to eq expected_array end end describe '#count' do it 'returns the number of items' do expect(model.count).to eq expected_array.size end end describe '#[]' do it 'returns the item for given index' do expect(model[1]).to eq(expected_array[1]) end end describe '#[]=' do it 'returns the assigned item' do item = additional_array[0] expect(model[2] = item).to eq item end context 'after called' do before do model[2] = additional_array[0] expected_array[2] = additional_array[0] end it_behaves_like 'same as expected array', 'sets the element to given index' it_behaves_like 'ListView data source' end end describe '#insert' do it 'returns self' do expect(model.insert(1, *additional_array)).to eq model end context 'after called' do before do model.insert(1, *additional_array) expected_array.insert(1, *additional_array) end it_behaves_like 'same as expected array', 'inserts item' it_behaves_like 'ListView data source' end end describe '#delete_at' do context 'with no number' do it 'deletes 1 item and returns it' do expect(model.delete_at(1)).to eq original_array[1] end context 'after called' do before do model.delete_at(1) expected_array.delete_at(1) end it_behaves_like 'same as expected array', 'deletes item' it_behaves_like 'ListView data source' end end context 'with number' do it 'deletes multiple items and returns them as an array' do expect(model.delete_at(1, 2)).to eq original_array[1..2] end context 'after called' do before do model.delete_at(1, 2) 2.times { expected_array.delete_at(1) } end it_behaves_like 'same as expected array', 'deletes items' it_behaves_like 'ListView data source' end end end describe '#unshift' do it 'prepends items' do expect(model.unshift(*additional_array).to_a).to eq expected_array.unshift(*additional_array) end end describe '#shift' do it 'removes first items and returns them' do expect(model.shift(2)).to eq expected_array[0..1] expect(model.to_a).to eq expected_array.tap { |a| a.shift(2) } end end describe '#push' do it 'appends items' do expect(model.push(*additional_array).to_a).to eq expected_array.push(*additional_array) end end describe '#pop' do it 'removes last items and returns them' do expect(model.pop(2)).to eq expected_array[-2..-1] expect(model.to_a).to eq expected_array.tap { |a| a.pop(2) } end end describe '#<<' do it 'is an alias of #push' do expect((model << additional_array[0]).to_a).to eq(expected_array << additional_array[0]) end end describe '#clear' do it 'returns self' do expect(model.clear).to be(model) end context 'after called' do before do model.clear expected_array.clear end it_behaves_like 'same as expected array', 'clears items' it_behaves_like 'ListView data source' end end describe '#replace' do it 'returns self' do expect(model.replace(expected_array + additional_array)).to be(model) end context 'after called' do before do model.replace(expected_array + additional_array) expected_array.push *additional_array end it_behaves_like 'same as expected array', 'replaces entire array' it_behaves_like 'ListView data source' end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/spec/qml/data/query_model_spec.rb
spec/qml/data/query_model_spec.rb
require 'spec_helper' describe QML::QueryModel do let(:klass) do Class.new(QML::QueryModel) do attr_accessor :data def initialize(count) @data = count.times.map { |i| {title: "title: #{i}", number: i} } super(:title, :number) end def query(offset, count) @data[offset ... offset + count] end def query_count @data.size end end end let(:model) { klass.new(2000) } let(:expected_array) { model.data } describe '#count' do it 'returns the count and updated by #update' do count = model.data.size expect(model.count).to eq(count) model.data << {value: 0} expect(model.count).to eq(count) model.update expect(model.count).to eq(count + 1) end end describe '#[]' do it 'returns the item' do model.data.size.times do |i| expect(model[i]).to eq(model.data[i]) end end end describe '#query_count' do it 'fails with NotImplementedError by default' do expect { QML::QueryModel.allocate.query_count }.to raise_error(NotImplementedError) end end describe '#query' do it 'fails with NotImplementedError by default' do expect { QML::QueryModel.allocate.query(0, 100) }.to raise_error(NotImplementedError) end end include_context 'ListView for model available' it_behaves_like 'ListView data source' do let(:model) { klass.new(10) } end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/spec/qml/data/list_model_spec.rb
spec/qml/data/list_model_spec.rb
require 'spec_helper' describe QML::ListModel do let(:model) { QML::ListModel.allocate } describe '#count' do it 'fails with NotImplementedError by default' do expect { model.count }.to raise_error(NotImplementedError) end end describe '#[]' do it 'fails with NotImplementedError by default' do expect { model[0] }.to raise_error(NotImplementedError) end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/spec/shared/qml/access_example.rb
spec/shared/qml/access_example.rb
class AccessExample include QML::Access property :text signal :some_signal, [:arg] def some_method(a, b) a + b end register_to_qml under: 'AccessExampleNS', version: '1.2', name: 'AccessExample' end module AccessExampleModule VERSION = '0.1.0' class AccessExample include QML::Access register_to_qml end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/spec/shared/qml/data/list_model.rb
spec/shared/qml/data/list_model.rb
shared_context 'ListView for model available' do let(:component) do QML::Component.new data: <<-EOS import QtQuick 2.0 ListView { model: ListModel {} delegate: Item { property var itemTitle: title property var itemNumber: number } } EOS end let(:list_view) { component.create } end shared_examples 'ListView data source' do it 'updates ListView correctly' do list_view.model = model count = list_view.count.to_i expect(count).to eq expected_array.size count.times do |i| list_view.currentIndex = i current = list_view.currentItem expect(current.itemTitle).to eq(expected_array[i][:title]) expect(current.itemNumber).to eq(expected_array[i][:number]) end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/examples/todo_sequel/todo_sequel.rb
examples/todo_sequel/todo_sequel.rb
$LOAD_PATH.unshift File.expand_path('../../../lib', __FILE__) require 'qml' require 'sequel' module Examples module Todo VERSION = '0.1' DB = Sequel.sqlite DB.create_table :todos do primary_key :id String :title String :description Time :due_date end class SequelModel < QML::QueryModel attr_accessor :dataset def initialize(dataset) @dataset = dataset super(*dataset.columns) end def query_count @dataset.count end def query(offset, count) @dataset.offset(offset).limit(count).all end end class TodoController include QML::Access register_to_qml def initialize super @todo_dataset = DB[:todos] self.model = SequelModel.new(@todo_dataset) end property(:title) { '' } property(:description) { '' } property(:due_date) { '' } property(:order_by) { '' } property :model def add @todo_dataset.insert(title: title, description: description, due_date: due_date.to_time) model.update end on_changed :order_by do model.dataset = @todo_dataset.order(order_by.to_sym) model.update end end end end QML.run do |app| app.load_path Pathname(__FILE__) + '../main.qml' end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/examples/twitter/twitter.rb
examples/twitter/twitter.rb
$LOAD_PATH.unshift File.expand_path('../../../lib', __FILE__) require 'qml' require 'twitter' require 'yaml' module Examples module Twitter VERSION = '0.1' class TweetFetcher def initialize config_data = YAML.load((Pathname(__FILE__) + '../config.yml').read) config_keys = %w{consumer_key consumer_secret access_token access_token_secret} @rest_client = ::Twitter::REST::Client.new do |config| config_keys.each do |key| config.public_send("#{key}=", config_data[key]) end end @streaming_client = ::Twitter::Streaming::Client.new do |config| config_keys.each do |key| config.public_send("#{key}=", config_data[key]) end end end def start(word) puts "word = #{word}" @rest_client.search(word).take(10).each do |t| yield t end @streaming_client.filter(track: word) do |object| case object when ::Twitter::Tweet yield object end end end end class TwitterController include QML::Access register_to_qml property(:model) { QML::ArrayModel.new(:tweet_text, :user_name, :user_icon) } property :word def initialize super() end def add_tweet(tweet) hash = {tweet_text: tweet.text, user_name: tweet.user.name, user_icon: tweet.user.profile_image_uri.to_s} puts hash model.unshift hash end def fetch_tweets model.clear if @thread @thread.kill end word = self.word @thread = Thread.new do TweetFetcher.new.start(word) do |tweet| QML.next_tick do add_tweet(tweet) end end end nil end end end end QML.run do |app| app.load_path Pathname(__FILE__) + '../main.qml' end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/examples/todo_array/todo_array.rb
examples/todo_array/todo_array.rb
$LOAD_PATH.unshift File.expand_path('../../../lib', __FILE__) require 'qml' require 'pathname' module Examples module Todo VERSION = '0.1' class TodoController include QML::Access register_to_qml property(:title) { '' } property(:description) { '' } property(:due_date) { '' } property(:model) { QML::ArrayModel.new(:title, :description, :due_date) } def add item = { title: title, description: description, due_date: due_date } p item model << item end end end end QML.run do |app| app.load_path Pathname(__FILE__) + '../main.qml' end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/examples/fizzbuzz/fizzbuzz.rb
examples/fizzbuzz/fizzbuzz.rb
$LOAD_PATH.unshift File.expand_path('../../../lib', __FILE__) require 'qml' require 'pathname' module Examples module FizzBuzz VERSION = '0.1' class FizzBuzz include QML::Access register_to_qml property(:input) { '0' } property(:result) { '' } signal :inputWasFizzBuzz, [] on_changed :input do i = input.to_i self.result = case when i % 15 == 0 inputWasFizzBuzz.emit "FizzBuzz" when i % 3 == 0 "Fizz" when i % 5 == 0 "Buzz" else i.to_s end end def quit puts "quitting..." QML.application.quit end end end end QML.run do |app| app.load_path Pathname(__FILE__) + '../main.qml' end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml.rb
lib/qml.rb
require 'qml/version' require 'qml/errors' require 'qml/qml' require 'qml/core_ext' require 'qml/plugin_loader' require 'qml/plugins' require 'qml/component' require 'qml/engine' require 'qml/application' require 'qml/signal' require 'qml/reactive' require 'qml/access' require 'qml/qt' require 'qml/root_path' require 'qml/js_object' require 'qml/js_array' require 'qml/js_util' require 'qml/proc_access' require 'qml/data'
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/plugins.rb
lib/qml/plugins.rb
require 'pathname' module QML # @api private module Plugins class << self def rubyqml @plugin ||= QML::PluginLoader.new(ROOT_PATH + "ext/qml/rubyqml-plugin", "rubyqml-plugin").instance end end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/platform.rb
lib/qml/platform.rb
module QML module Platform module_function def windows? !!(/cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM) end def mac? !!(/darwin/ =~ RUBY_PLATFORM) end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/component.rb
lib/qml/component.rb
require 'qml/engine' module QML # The Component class is used to instantiate objects like Window / ApplicationWindow objects from QML files. # # You usually do not need to use this class because Application#load, #load_path, #load_data do same # for the application top-level objects such as main windows. # @example # component = Component.new(engine: engine, path: path_to_qml_file) # root_object = component.create # @see http://qt-project.org/doc/qt-5/qqmlcomponent.html QQmlComponent (C++) class Component attr_reader :data, :path # Creates an component. Either data or path must be specified. # @param [String] data the QML file data. # @param [#to_s] path the QML file path. # @return QML::Component def initialize(data: nil, path: nil) fail TypeError, "neither data nor path privided" unless data || path initialize_impl case when data load_data(data) when path load_path(path) end end def load_path(path) path = path.to_s check_error_string do @path = Pathname.new(path) load_path_impl(path) end self end def load_data(data) check_error_string do @data = data load_data_impl(data, "<<STRING>>") end self end # Instantiates a object from the QML file. # @return [QML::JSObject] The created object def create check_error_string do create_impl end end private def check_error_string yield.tap do fail QMLError, error_string if error_string end end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/data.rb
lib/qml/data.rb
require 'qml/data/list_model_access' require 'qml/data/list_model' require 'qml/data/array_model' require 'qml/data/query_model'
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/root_path.rb
lib/qml/root_path.rb
module QML ROOT_PATH = Pathname.new(__FILE__) + '../../..' end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/version.rb
lib/qml/version.rb
module QML VERSION = '1.0.2' end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/application.rb
lib/qml/application.rb
module QML # {Application} represents a Qt application instance. # It provides the event loop and manages Application-level configurations. # # @see http://qt-project.org/doc/qt-5/qapplication.html QApplication (C++) class Application # @return [Engine] The engine of the application. def engine QML.engine end # @return [Component] The root component of the application that represents the loaded QML file. # @see #load # @see #load_data # @see #load_path def root_component @root_component or fail ApplicationError, "QML data or file has not been loaded" end # Loads a QML file. The loaded component can be accessed by {#root_component} # @param [String] data # @param [String] path # @see Component def load(data: nil, path: nil) @root_component = Component.new(data: data, path: path) @root = @root_component.create end # Loads a QML file from string data. # @see #load def load_data(data) load(data: data) end # Loads a QML file from a file path. # @see #load def load_path(path) load(path: path) end # @return The root object created by the root component. def root @root or fail "QML data or file has not been loaded" end # Quits the application. def quit QML.qt.quit end end INIT_BLOCKS = [] module_function def on_init(&block) INIT_BLOCKS << block end # Initializes ruby-qml. # @param [Array<String>] args Arguments to pass to the application def init(args = []) init_impl(args) end # Creates an {Application}, yields it and then call {QML::Application#exec}. # @return [Application] # @example # QML.run do |app| # app.load_path Pathname(__FILE__) + '../main.qml' # end def run QML.init QML.application.tap do |app| yield app app.exec end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/core_ext.rb
lib/qml/core_ext.rb
require 'qml/core_ext/to_qml'
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/errors.rb
lib/qml/errors.rb
module QML class PluginError < StandardError; end class QMLError < StandardError; end class AccessError < StandardError; end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/plugin_loader.rb
lib/qml/plugin_loader.rb
require 'pathname' require 'qml/platform' module QML # {PluginLoader} loads Qt C++ plugins and enables you to use your Qt C++ codes from Ruby easily. # @see http://qt-project.org/doc/qt-5/qpluginloader.html QPluginLoader (C++) class PluginLoader # @overload initialize(path) # @param [String|Pathname] path the library path (may be platform-dependent). # @example # loader = QML::PluginLoader.new('path/to/libhoge.dylib') # @overload initialize(dir, libname) # @param [String|Pathname] dir the library directory. # @param [String] libname the platform-independent library name. # @example # loader = QML::PluginLoader.new('path/to', 'hoge') def initialize(path, libname = nil) path = Pathname(path) + self.class.lib_filename(libname) if libname initialize_impl(path.to_s) end def self.lib_filename(libname) case when Platform::windows? "#{libname}.dll" when Platform::mac? "lib#{libname}.dylib" else "lib#{libname}.so" end end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/js_array.rb
lib/qml/js_array.rb
module QML class JSArray < JSObject # @return [Array] def to_a each.to_a end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/interface.rb
lib/qml/interface.rb
module QML module Interface def self.call_method(obj, name, args) begin obj.__send__ name, *args rescue => error notify_error(error) nil end end # Called when an Ruby error is occured in executing Qt code. # @param error The error (or the exception) def self.notify_error(error) warn "-- An error occured when running Ruby code from Qt --" warn "#{error.class.name}: #{error.message}" warn "Backtrace: \n\t#{error.backtrace.join("\n\t")}" end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/reactive.rb
lib/qml/reactive.rb
module QML module Reactive # @!parse extend ClassMethods # @api private class PropertyInfo attr_accessor :initializer end # @api private class SignalInfo attr_accessor :params attr_accessor :listeners def initialize @listeners = [] end end def initialize(*args, &block) self.class.property_infos.each do |name, info| if info.initializer self.__send__ :"#{name}=", instance_eval(&info.initializer) end end self.class.signal_infos.each do |name, info| __send__(name).connect do |*args| info.listeners.each do |listener| instance_exec(*args, &listener) end end end super end def self.included(derived) derived.class_eval do extend ClassMethods end end module ClassMethods # @api public # Defines a signal. # @example # class Button # include QML::Reactive::Object # signal :pressed, [:pos] # ... # end def signal(name, params = []) name = name.to_sym signal_infos(false)[name] = SignalInfo.new.tap do |info| info.params = params.map(&:to_sym) end class_eval <<-EOS, __FILE__, __LINE__ + 1 def #{name} @_signal_#{name} ||= begin args = self.class.signal_infos[:#{name}].params Signal.new(args) end end EOS name end private :signal def signals(include_super = true) signal_infos(include_super).keys end def signal_infos(include_super = true) if include_super && superclass.include?(Access) superclass.signal_infos.merge(signal_infos(false)) else @signal_infos ||= {} end end # Defines a property. # @example # class Foo # include QML::Access # property(:name) { 'hogehoge' } # ... # end def property(name, &block) name = name.to_sym signal(:"#{name}_changed", [:"new_#{name}"]) property_infos(false)[name] = PropertyInfo.new.tap do |info| info.initializer = block end class_eval <<-EOS, __FILE__, __LINE__ + 1 attr_reader :#{name} def #{name}=(new_value) new_value = new_value if @#{name} != new_value @#{name} = new_value #{name}_changed.emit(new_value) end end EOS name end private :property def properties(include_super = true) property_infos(include_super).keys end def property_infos(include_super = true) if include_super && superclass.include?(Access) superclass.property_infos.merge(property_infos(false)) else @property_infos ||= {} end end def on(signal, &block) info = signal_infos(false)[signal.to_sym] or fail AccessError, "no signal `#{signal}` found" info.listeners << block block end def on_changed(property, &block) on(:"#{property}_changed", &block) end private :on, :on_changed end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/qml.rb
lib/qml/qml.rb
require_relative '../../ext/qml/qml'
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/js_util.rb
lib/qml/js_util.rb
module QML module JSUtil def self.data @data ||= QML.engine.evaluate <<-JS ({ classes: { Date: Date } }) JS end def self.classes data.classes end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/access.rb
lib/qml/access.rb
module QML # {Access} enables classes to be exposed to QML. # module Access # @!parse include Reactive # @!parse extend ClassMethods def set_signal_emitter(emitter) self.class.signals.each do |name| __send__(name).connect do |*args| emitter.emit(name, args) end end end private :set_signal_emitter def self.included(derived) derived.class_eval do include Reactive extend ClassMethods end end def to_qml @qml_value ||= self.class.meta_class.wrap(self) end # allowed name patterns for exposed method names ALLOWED_PATTERN = /^[a-zA-Z_]\w*$/ module ClassMethods def meta_class @meta_class ||= begin meta_class = MetaClass.new(self, name) signals = self.signals.grep(ALLOWED_PATTERN) properties = self.properties.grep(ALLOWED_PATTERN) signals.each do |signal| meta_class.add_signal(signal, signal_infos[signal].params) end properties.each do |prop| meta_class.add_property(prop, :"#{prop}_changed") end methods = ancestors.take_while { |k| k.include?(Access) } .map { |k| k.instance_methods(false) }.inject(&:|) .grep(ALLOWED_PATTERN) ignored_methods = signals | properties.flat_map { |p| [p, :"#{p}=", :"#{p}_changed"] } (methods - ignored_methods).each do |method| instance_method = self.instance_method(method) # ignore variadic methods if instance_method.arity >= 0 meta_class.add_method(method, instance_method.arity) end end meta_class end end # Registers the class as a QML type. # @param opts [Hash] # @option opts [String] :under the namespece which encapsulates the exported QML type. If not specified, automatically inferred from the module nesting of the class. # @option opts [String] :version the version of the type. Defaults to VERSION constant of the encapsulating module / class of the class. # @option opts [String] :name the name of the type. Defaults to the name of the class. def register_to_qml(opts = {}) QML.on_init do register_to_qml_impl(opts) end end def register_to_qml_impl(opts) metadata = guess_metadata(opts) meta_class.register( metadata[:under], metadata[:versions][0], metadata[:versions][1], metadata[:name] ) end private def guess_metadata(opts) under = opts[:under] version = opts[:version] name = opts[:name] if !under || !version || !name path = self.name.split('::') end if !under && !version fail AccessError, "cannot guess namespace of toplevel class '#{self.name}'" if path.size == 1 encapsulatings = path[0, path.size - 1] end under ||= encapsulatings.join('.') version ||= eval("::#{encapsulatings.join('::')}").const_get(:VERSION) versions = version.split('.').map(&method(:Integer)) fail AccessError, 'insufficient version (major and minor versions required)' unless versions.size >= 2 name ||= path.last {under: under, versions: versions, name: name} end end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/js_object.rb
lib/qml/js_object.rb
module QML # The JSObject represents JavaScript objects. class JSObject alias_method :each, :each_pair # @return [Array<String>] def keys each.map { |k, v| k } end # @return [Array] def values each.map { |k, v| v } end # @return [Hash] def to_hash {}.tap do |hash| each do |k, v| hash[k] =v end end end # @return [Time] def to_time Time.at(getTime.to_i / 1000r).getlocal(-getTimezoneOffset * 60) end # @return [QML::QMLError] def to_error QMLError.new(self['message']) end def respond_to?(method) has_key?(method) || super end # Gets or sets a JS property, or call it as a method if it is a function. def method_missing(method, *args, &block) if method[-1] == '=' # setter key = method.slice(0...-1).to_sym unless has_key?(key) super end self[key] = args[0] else unless has_key?(method) super end prop = self[method] if prop.is_a? JSFunction prop.call_with_instance(self, *args, &block) else prop end end end # @return [QML::JSObject] self def to_qml self end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/proc_access.rb
lib/qml/proc_access.rb
module QML class ProcAccess include Access register_to_qml under: 'RubyQml', version: QML::VERSION def call(args) @proc.call(*args) end # @return [QML::JSFunction] def self.wrap_proc(prc) @bind_call ||= QML.engine.evaluate <<-JS (function (access) { return access.call.bind(access); }) JS @component ||= QML::Component.new(data: <<-QML) import RubyQml 1.0 ProcAccess {} QML access = @component.create access.unwrap.instance_eval do @proc = prc end @bind_call.call(access) end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/qt.rb
lib/qml/qt.rb
module QML module_function # @example # def set_app_name # QML.qt.application.name = 'appname' # end # @return [JSObject] QML Qt namespace object # @see http://doc.qt.io/qt-5/qml-qtqml-qt.html def qt @qt ||= begin component = QML::Component.new data: <<-QML import QtQuick 2.0 QtObject { function getQt() { return Qt; } } QML component.create.getQt end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/engine.rb
lib/qml/engine.rb
module QML # @!parse class Engine < QtObjectBase; end # {Engine} provides a QML engine. # # @see http://qt-project.org/doc/qt-5/qqmlengine.html QQmlEngine (C++) class Engine # Evaluates an JavaScript expression # @param [String] str The JavaScript string # @param [String] file The file name # @param [Integer] lineno The line number def evaluate(str, file = '<in QML::Engine#evaluate>', lineno = 1) evaluate_impl(str, file, lineno).tap do |result| raise result.to_error if result.is_a?(JSObject) && result.error? end end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/name_helper.rb
lib/qml/name_helper.rb
module QML module NameHelper module_function def to_underscore(sym) sym.to_s.gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').gsub(/([a-z\d])([A-Z])/,'\1_\2').downcase.to_sym end def to_upper_underscore(sym) to_underscore(sym).upcase end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/signal.rb
lib/qml/signal.rb
module QML class Signal class Connection def initialize(signal, listener) @signal = signal @listener = listener end # Disconnects the connection. def disconnect @signal.disconnect(@listener) end end attr_reader :arity # Initializes the Signal. # @param [Array<#to_sym>, nil] params the parameter names (the signal will be variadic if nil). def initialize(params) @listeners = [] @params = params.map(&:to_sym) @arity = params.size end # Calls every connected procedure with given arguments. # Raises an ArgumentError when the arity is wrong. # @param args the arguments. def emit(*args) if args.size != @arity fail ::ArgumentError ,"wrong number of arguments for signal (#{args.size} for #{@arity})" end @listeners.each do |listener| listener.call(*args) end end # Returns the format of the parameters in the same format as Proc#parameters. # @return [Array<Array<Symbol>>] def parameters @params ? @params.map { |arg| [:req, arg] } : [[:rest, :args]] end # Returns the number of connections. # @return [Integer] def connection_count @listeners.size end # Connects a procedure. # @yield called when #emit is called. # @return [QML::Signal::Connection] def connect(&listener) @listeners << listener Connection.new(self, listener) end # Disconnects a procedure. # @param listener # @return [self] def disconnect(listener) @listeners.delete(listener) self end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/core_ext/to_qml.rb
lib/qml/core_ext/to_qml.rb
class Numeric def to_qml to_f end end class String def to_qml self end end class Symbol def to_qml to_s end end class TrueClass def to_qml self end end class FalseClass def to_qml self end end class NilClass def to_qml self end end class Array def to_qml QML.engine.new_array(self.size).tap do |jsarray| self.each_with_index do |x, i| jsarray[i] = x end end end end class Hash def to_qml QML.engine.new_object.tap do |jsobj| self.each do |key, value| jsobj[key] = value end end end end class Time def to_qml QML::JSUtil.classes['Date'].new(year, month, day, hour, min, sec, nsec / 1000000).tap do |date| date.setTime((to_r * 1000).floor) end end end class Proc def to_qml QML::ProcAccess.wrap_proc(self) end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/data/query_model.rb
lib/qml/data/query_model.rb
module QML # {QueryModel} provides a list model implementation with database backends like ActiveRecord. class QueryModel < ListModel attr_reader :count # @param [Array<Symbol|String>] columns def initialize(*columns) super @count = 0 @caches = [] update end def [](index) block_index = index / CACHE_SIZE cache = @caches.find { |c| c.block_index == block_index } || add_cache(block_index) cache.items[index % CACHE_SIZE] end # Updates the model. def update @caches = [] resetting do @count = query_count end end # @abstract # Queries the count of the records. # Called when {#update} is called and the result is set as the {#count} of the model. # @return [Integer] def query_count fail ::NotImplementedError end # @abstract # Queries a block of records. The results are chached. # @param [Integer] offset # @param [Integer] count # @return [Array] def query(offset, count) fail ::NotImplementedError end private Cache = Struct.new(:block_index, :items) CACHE_SIZE = 256 CACHE_COUNT = 4 def add_cache(block_offset) @caches.shift if @caches.size >= CACHE_COUNT Cache.new(block_offset, query(block_offset * CACHE_SIZE, CACHE_SIZE)).tap do |cache| @caches << cache end end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/data/list_model_access.rb
lib/qml/data/list_model_access.rb
module QML # @api private class ListModelAccess include Access signal :begin_insert, [:first, :last] signal :end_insert signal :begin_move, [:first, :last, :dest] signal :end_move signal :begin_remove, [:first, :last] signal :end_remove signal :update, [:first, :last] signal :begin_reset signal :end_reset attr_accessor :model def columns @model.columns.to_qml end def data(index, column) @model[index.to_i][column.to_sym].to_qml end def count @model.count end register_to_qml under: 'RubyQml', version: QML::VERSION # @return [QML::JSWrapper] def self.create(model) @component ||= QML::Component.new(data: <<-QML) import RubyQml 1.0 ListModelAccess {} QML @component.create.tap do |access| access.unwrap.model = model end end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/data/array_model.rb
lib/qml/data/array_model.rb
module QML # {ArrayModel} is one of ruby-qml's list models and it stores data in Array simply. class ArrayModel < ListModel # @param [Array<Symbol|String>] columns def initialize(*columns) super @array = [] end # Duplicates the internal array and returns it. # @return [Array] def to_a @array.dup end # @return [Integer] the number of the items. def count @array.count end # Returns an item. # @param [Integer] index the index of the item. # @return the item. def [](index) @array[index] end # Updates an item. # @param [Integer] index # @param item # @return the item. def []=(index, item) @array[index] = item update(index .. index) item end # Inserts items. # @param [Integer] index # @return [self] def insert(index, *items) inserting(index ... index + items.size) do @array.insert(index, *items) end self end # @overload delete_at(index) # Deletes an item. # @param [Integer] index # @return the deleted item. # @overload delete_at(index, count) # Deletes items. # @param [Integer] index # @return [Array] the deleted items. def delete_at(index, count = nil) if count removing(index ... index + count) do count.times.map { @array.delete_at(index) } end else removing(index .. index) do @array.delete_at(index) end end end # Prepend items. # @return [self] def unshift(*items) insert(0, *items) end # @overload shift # Deletes the first item. # @return the deleted item. # @overload shift(count) # Deletes the first items. # @return [Array] the deleted items. def shift(count = nil) delete_at(0, count) end # Append items. # @return [self] def push(*items) insert(@array.size, *items) end alias_method :<<, :push # @overload pop # Deletes the last item. # @return the deleted item. # @overload pop(count) # Deletes the last items. # @return [Array] the deleted items. def pop(count = nil) delete_at(@array.size - count, count) end # Deletes all items. # @return [self] def clear removing(0 ... count) do @array.clear end self end # Replaces entire array with given array. # @param [Array] ary # @return [self] def replace(ary) resetting do @array = ary.dup end self end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
seanchas116/ruby-qml
https://github.com/seanchas116/ruby-qml/blob/569af4c31460d2946c18346dc94751c77b1d4dfc/lib/qml/data/list_model.rb
lib/qml/data/list_model.rb
module QML # {ListModel} is the base class of list models which provides data to QML list views. # @see http://qt-project.org/doc/qt-5/qabstractitemmodel.html QAbstractItemModel (C++) # @see http://qt-project.org/doc/qt-5/qabstractlistmodel.html QAbstractListModel (C++) class ListModel include Enumerable # @return [Array<Symbol|String>] attr_reader :columns # @param [Array<Symbol|String>] columns the column names of the model. def initialize(*columns) @columns = columns @access = ListModelAccess.create(self) @qml_model = QML::Plugins.rubyqml.createListModel(@access) end # Iterates each item. # @overload each # @return [Enumerator] # @overload each # @yield [item] # @return [self] def each return to_enum unless block_given? count.times do |i| yield self[i] end self end # @abstract # @return [Integer] the number of the items. def count fail ::NotImplementedError end # Returns an item. # @abstract # @param [Integer] index the index of the item. # @return the item. def [](index) fail ::NotImplementedError end # @return [QML::JSObject] def to_qml @qml_model end protected # Notifies the list views that the data of the items was changed. # @param [Range<Integer>] range the index range of changed items. def update(range) @access.update(range.min, range.max) end # Notifies the list views that items are about to be and were moved. # @param [Range<Integer>] range the index range of the item being moved. # @param [Integer] destination the first index of the items after moved. # @yield the block that actually do moving operation of the items. # @return the result of given block. # @see http://qt-project.org/doc/qt-5/qabstractitemmodel.html#beginMoveRows QAbstractItemModel::beginMoveRows # @see http://qt-project.org/doc/qt-5/qabstractitemmodel.html#endMoveRows QAbstractItemModel::endMoveRows # @see #inserting # @see #removing def moving(range, destination) return if range.count == 0 @access.begin_move(range.min, range.max, destination) ret = yield @access.end_move ret end # Notifies the list views that items are about to be and were inserted. # @param [Range<Integer>] range the index range of the items after inserted. # @yield the block that actually do insertion of the items. # @return the result of give block. # @example # inserting(index ... index + items.size) do # @array.insert(index, *items) # end # @see http://qt-project.org/doc/qt-5/qabstractitemmodel.html#beginInsertRows QAbstractItemModel::beginInsertRows # @see http://qt-project.org/doc/qt-5/qabstractitemmodel.html#endInsertRows QAbstractItemModel::endInsertRows # @see #removing # @see #moving def inserting(range, &block) return if range.count == 0 @access.begin_insert(range.min, range.max) ret = yield @access.end_insert ret end # Notifies the list views that items are about to be and were removed. # @param [Range<Integer>] range the index range of the items before removed. # @yield the block that actually do removal of the items. # @return the result of give block. # @see http://qt-project.org/doc/qt-5/qabstractitemmodel.html#beginRemoveRows QAbstractItemModel::beginRemoveRows # @see http://qt-project.org/doc/qt-5/qabstractitemmodel.html#endRemoveRows QAbstractItemModel::endRemoveRows # @see #inserting # @see #moving def removing(range, &block) return if range.count == 0 @access.begin_remove(range.min, range.max) ret = yield @access.end_remove ret end def resetting(&block) @access.begin_reset ret = yield @access.end_reset ret end end end
ruby
MIT
569af4c31460d2946c18346dc94751c77b1d4dfc
2026-01-04T17:45:04.102420Z
false
inkstak/activejob-status
https://github.com/inkstak/activejob-status/blob/e0ff3934073a9caa47a5f20261ed3bd5e6a3fc84/spec/spec_helper.rb
spec/spec_helper.rb
# frozen_string_literal: true require "bundler/setup" Bundler.setup unless RUBY_ENGINE == "truffleruby" require "simplecov" SimpleCov.start end require "active_job" require "activejob-status" require "timecop" Dir.mkdir("tmp") unless Dir.exist?("tmp") ActiveJob::Base.queue_adapter = :test ActiveJob::Base.logger = ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(File.open("tmp/log", "w"))) ActiveJob::Status.store = :memory_store RSpec.configure do |config| config.order = "random" config.expect_with :rspec do |expect| expect.syntax = :expect end config.include ActiveJob::TestHelper config.before do ActiveJob::Status.options = ActiveJob::Status::DEFAULT_OPTIONS end config.after do Timecop.return end end
ruby
MIT
e0ff3934073a9caa47a5f20261ed3bd5e6a3fc84
2026-01-04T17:45:06.564606Z
false
inkstak/activejob-status
https://github.com/inkstak/activejob-status/blob/e0ff3934073a9caa47a5f20261ed3bd5e6a3fc84/spec/jobs/test_jobs.rb
spec/jobs/test_jobs.rb
# frozen_string_literal: true class BaseJob < ActiveJob::Base include ActiveJob::Status def perform end end class AsyncJob < BaseJob self.queue_adapter = :async def perform(sleep_time = 1) sleep(sleep_time) end end class FailedJob < BaseJob def perform raise "Something went wrong" end end class MethodErrorJob < BaseJob def perform raise NoMethodError, "Something went wrong" end end class ProgressJob < BaseJob def perform progress.total = 100 progress.increment(40) end end class CustomPropertyJob < BaseJob def perform status[:step] = "A" end end class UpdateJob < BaseJob def perform status.update(step: "B", progress: 25, total: 50) end end class ThrottledJob < BaseJob def status @status ||= ActiveJob::Status::Status.new(self, throttle_interval: 0.5) end end class ThrottledSettersJob < ThrottledJob def perform status[:step] = "A" progress.progress = 0 progress.total = 10 status[:step] = "B" progress.progress = 1 progress.total = 20 status[:step] = "C" progress.progress = 2 progress.total = 30 end end class ThrottledUpdatesJob < ThrottledJob def perform status.update(step: "A", progress: 0, total: 10) status.update(step: "B", progress: 1, total: 20) status.update(step: "C", progress: 2, total: 30) end end class ThrottledForcedUpdatesJob < ThrottledJob def perform status.update({step: "A", progress: 0, total: 10}, force: true) status.update({step: "B", progress: 1, total: 20}, force: true) status.update({step: "C", progress: 2, total: 30}, force: true) end end
ruby
MIT
e0ff3934073a9caa47a5f20261ed3bd5e6a3fc84
2026-01-04T17:45:06.564606Z
false
inkstak/activejob-status
https://github.com/inkstak/activejob-status/blob/e0ff3934073a9caa47a5f20261ed3bd5e6a3fc84/spec/specs/active_job/status_spec.rb
spec/specs/active_job/status_spec.rb
# frozen_string_literal: true require_relative "../../spec_helper" require_relative "../../jobs/test_jobs" RSpec.describe ActiveJob::Status do # FIXME: weird error on JRUBY, happening randomly, # where keyword arguments are not passed as keyword arguments but with regular # arguments # if RUBY_ENGINE == "jruby" && Gem::Version.new(JRUBY_VERSION) >= Gem::Version.new("9.4") def jobs_with(*args, **kwargs) super rescue ArgumentError super(args[0], **args[1]) if kwargs.empty? end end describe "job status instance" do it "is assigned when job is initialized" do job = BaseJob.new expect(job.status).to be_an(ActiveJob::Status::Status) end it "is assigned when is enqueued" do job = BaseJob.perform_later expect(job.status).to be_an(ActiveJob::Status::Status) end it "is retrieved using job instance" do job = BaseJob.perform_later expect(described_class.get(job)).to be_an(ActiveJob::Status::Status) end it "is retrieved using job ID" do job = BaseJob.perform_later expect(described_class.get(job.job_id)).to be_an(ActiveJob::Status::Status) end end describe "job status key" do it "is assigned to `queued` after the job is enqueued" do job = BaseJob.perform_later expect(job.status.to_h).to eq(status: :queued) end it "is assigned to 'working` while the job is performed" do job = AsyncJob.perform_later(2) sleep(0.1) # Give time to async thread pool to start the job expect(job.status.to_h).to eq(status: :working) AsyncJob.queue_adapter.shutdown(wait: false) end it "is assigned to `completed` after the is performed" do job = BaseJob.perform_later perform_enqueued_jobs expect(job.status.to_h).to eq(status: :completed) end it "is assigned to `failed` when an exception is raised" do job = FailedJob.perform_later aggregate_failures do expect { perform_enqueued_jobs }.to raise_error(RuntimeError) expect(job.status.to_h).to eq(status: :failed) end end context "when status is not included by default" do before do described_class.options = {includes: []} end it "isn't assigned after the job is enqueued" do job = BaseJob.perform_later expect(job.status.to_h).to eq({}) end it "isn't assigned after the job is performed" do job = BaseJob.perform_later perform_enqueued_jobs expect(job.status.to_h).to eq({}) end end end describe "job progress" do it "is assigned to the job instance" do job = BaseJob.new expect(job.progress).to be_an(ActiveJob::Status::Progress) end it "is updated from inside the job" do job = ProgressJob.perform_later perform_enqueued_jobs aggregate_failures do expect(job.status.to_h).to include(progress: 40, total: 100) expect(job.status.progress).to eq(0.4) end end it "reads cache once" do job = BaseJob.new allow(described_class.store).to receive(:read) job.status.progress expect(described_class.store).to have_received(:read).once end end describe "job status" do it "updates custom property using []=" do job = CustomPropertyJob.perform_later perform_enqueued_jobs expect(job.status.to_h).to include(step: "A") end it "updates multiple properties using #update" do job = UpdateJob.perform_later perform_enqueued_jobs expect(job.status.to_h).to include(step: "B", progress: 25, total: 50) end it "updates job progress when using #update" do job = UpdateJob.perform_later job.perform aggregate_failures do expect(job.progress.progress).to eq(25) expect(job.progress.total).to eq(50) end end it "retrieves all updated properties" do job = UpdateJob.perform_later status = described_class.get(job.job_id) expect { perform_enqueued_jobs } .to change(status, :to_h) .to(status: :completed, step: "B", progress: 25, total: 50) end it "updates custom property from the outside using []=" do job = BaseJob.perform_later status = described_class.get(job.job_id) status[:step] = "A" expect(job.status.to_h).to include(step: "A") end it "updates job progress from the outside using []=" do job = BaseJob.perform_later status = described_class.get(job.job_id) status[:progress] = 1 status[:total] = 5 expect(job.status.to_h).to include(progress: 1, total: 5) end it "updates multiple properties from the outside using #update" do job = BaseJob.perform_later status = described_class.get(job.job_id) status.update(step: "C", progress: 24, total: 48) expect(job.status.to_h).to include(step: "C", progress: 24, total: 48) end end describe "throttling" do it "is ignored when updating status using []=" do job = ThrottledSettersJob.perform_later perform_enqueued_jobs expect(job.status.to_h).to include(status: :completed, step: "C", progress: 2, total: 30) end it "is limiting updates in a time interval when using #update" do job = ThrottledUpdatesJob.perform_later perform_enqueued_jobs expect(job.status.to_h).to include(status: :completed) end it "is bypassed when using :force parameter in #update" do job = ThrottledForcedUpdatesJob.perform_later perform_enqueued_jobs expect(job.status.to_h).to include(status: :completed, step: "C", progress: 2, total: 30) end end context "when serialized job is included by default" do before do Timecop.freeze("2022-10-31T00:00:00Z") described_class.options = {includes: %i[status serialized_job]} end it "sets job status to queued after being enqueued" do job = BaseJob.perform_later expect(job.status.to_h).to eq( status: :queued, serialized_job: { "arguments" => [], "enqueued_at" => "2022-10-31T00:00:00.000000000Z", "exception_executions" => {}, "executions" => 0, "job_class" => "BaseJob", "job_id" => job.job_id, "locale" => "en", "priority" => nil, "provider_job_id" => nil, "queue_name" => "default", "scheduled_at" => nil, "timezone" => nil }.tap { |hash| # FIXME: comparing Gem::Version with String doesn't work in ruby 3.0 # After removing support for 3.0, we could do # ActiveJob.version < "7.1" # if ActiveJob.version < Gem::Version.new("7.1") hash["enqueued_at"] = "2022-10-31T00:00:00Z" hash.delete("scheduled_at") end } ) end it "sets job status to completed after being performed" do job = BaseJob.perform_later perform_enqueued_jobs expect(job.status.to_h).to eq( status: :completed, serialized_job: { "arguments" => [], "enqueued_at" => "2022-10-31T00:00:00.000000000Z", "exception_executions" => {}, "executions" => 1, "job_class" => "BaseJob", "job_id" => job.job_id, "locale" => "en", "priority" => nil, "provider_job_id" => nil, "queue_name" => "default", "scheduled_at" => nil, "timezone" => nil }.tap { |hash| if ActiveJob.version < Gem::Version.new("7.1") hash["enqueued_at"] = "2022-10-31T00:00:00Z" hash.delete("scheduled_at") end } ) end end context "when exception is included by default" do before do described_class.options = {includes: %i[status exception]} end it "sets job status to failed after an exception is raised" do job = FailedJob.perform_later aggregate_failures do expect { perform_enqueued_jobs }.to raise_error(RuntimeError) expect(job.status.to_h).to eq( status: :failed, exception: {class: "RuntimeError", message: "Something went wrong"} ) end end it "returns origin message from failure, without DidYouMean suggestions" do job = MethodErrorJob.perform_later aggregate_failures do expect { perform_enqueued_jobs }.to raise_error(NoMethodError) expect(job.status.to_h).to eq( status: :failed, exception: {class: "NoMethodError", message: "Something went wrong"} ) end end end end
ruby
MIT
e0ff3934073a9caa47a5f20261ed3bd5e6a3fc84
2026-01-04T17:45:06.564606Z
false
inkstak/activejob-status
https://github.com/inkstak/activejob-status/blob/e0ff3934073a9caa47a5f20261ed3bd5e6a3fc84/lib/activejob-status.rb
lib/activejob-status.rb
# frozen_string_literal: true require "active_support/concern" require "active_support/core_ext/hash" require "active_support/core_ext/enumerable" require "active_job" require "activejob-status/storage" require "activejob-status/status" require "activejob-status/progress" require "activejob-status/throttle" module ActiveJob module Status extend ActiveSupport::Concern DEFAULT_OPTIONS = { expires_in: 60 * 30, throttle_interval: 0, includes: %i[status] }.freeze included do before_enqueue { |job| job.status.update_defaults(:queued) } before_perform { |job| job.status.update_defaults(:working) } after_perform { |job| job.status.update_defaults(:completed) } rescue_from(Exception) do |e| status.catch_exception(e) raise e end end def status @status ||= Status.new(self) end def progress @progress ||= Progress.new(self) end class << self def options=(options) options.assert_valid_keys(*DEFAULT_OPTIONS.keys) @@options = DEFAULT_OPTIONS.merge(options) end def options @@options ||= DEFAULT_OPTIONS end def store=(store) store = ActiveSupport::Cache.lookup_store(*store) if store.is_a?(Array) || store.is_a?(Symbol) @@store = store end def store @@store ||= (Rails.cache if defined?(Rails)) end def get(id) Status.new(id) end end end end
ruby
MIT
e0ff3934073a9caa47a5f20261ed3bd5e6a3fc84
2026-01-04T17:45:06.564606Z
false
inkstak/activejob-status
https://github.com/inkstak/activejob-status/blob/e0ff3934073a9caa47a5f20261ed3bd5e6a3fc84/lib/activejob-status/storage.rb
lib/activejob-status/storage.rb
# frozen_string_literal: true module ActiveJob module Status class Storage def initialize(options = {}) options.assert_valid_keys(:expires_in, :throttle_interval) @expires_in = options[:expires_in] @throttle = ActiveJob::Status::Throttle.new(options[:throttle_interval]) end def store @store ||= ActiveJob::Status.store end def job_id(job) job.is_a?(String) ? job : job.job_id end def key(job) "activejob:status:#{job_id(job)}" end def read(job) store.read(key(job)) || {} end def write(job, message, force: false) @throttle.wrap(force: force) do store.write(key(job), message, expires_in: @expires_in) end end def update(job, message, force: false) @throttle.wrap(force: force) do message = read(job).merge(message) store.write(key(job), message, expires_in: @expires_in) end end def delete(job) store.delete(key(job)) end end end end
ruby
MIT
e0ff3934073a9caa47a5f20261ed3bd5e6a3fc84
2026-01-04T17:45:06.564606Z
false
inkstak/activejob-status
https://github.com/inkstak/activejob-status/blob/e0ff3934073a9caa47a5f20261ed3bd5e6a3fc84/lib/activejob-status/version.rb
lib/activejob-status/version.rb
# frozen_string_literal: true module ActiveJob module Status VERSION = "1.0.2" end end
ruby
MIT
e0ff3934073a9caa47a5f20261ed3bd5e6a3fc84
2026-01-04T17:45:06.564606Z
false
inkstak/activejob-status
https://github.com/inkstak/activejob-status/blob/e0ff3934073a9caa47a5f20261ed3bd5e6a3fc84/lib/activejob-status/throttle.rb
lib/activejob-status/throttle.rb
# frozen_string_literal: true module ActiveJob module Status class Throttle def initialize(interval) @interval = interval @started_at = Time.current end def wrap(force: false) return yield if force || @interval.nil? || @interval.zero? now = Time.current elasped = now - @started_at return if @interval > elasped yield @started_at = now end end end end
ruby
MIT
e0ff3934073a9caa47a5f20261ed3bd5e6a3fc84
2026-01-04T17:45:06.564606Z
false
inkstak/activejob-status
https://github.com/inkstak/activejob-status/blob/e0ff3934073a9caa47a5f20261ed3bd5e6a3fc84/lib/activejob-status/status.rb
lib/activejob-status/status.rb
# frozen_string_literal: true module ActiveJob module Status class Status delegate :[], :to_s, :to_json, :inspect, to: :read delegate :queued?, :working?, :completed?, :failed?, to: :status_inquiry def initialize(job, options = {}) options = ActiveJob::Status.options.merge(options) @defaults = options.fetch(:includes, []) @storage = ActiveJob::Status::Storage.new(options.without(:includes)) @job = job end def []=(key, value) update({key => value}, force: true) end def read @storage.read(@job) end alias_method :to_h, :read def update(payload, options = {}) if @job.respond_to?(:progress) @job.progress.instance_variable_set(:@progress, payload[:progress]) if payload.include?(:progress) @job.progress.instance_variable_set(:@total, payload[:total]) if payload.include?(:total) end @storage.update(@job, payload, **options) end def delete @storage.delete(@job) end def job_id @storage.job_id(@job) end def status read[:status] end def progress read.then do |hash| hash[:progress].to_f / hash[:total].to_f end end def present? read.present? end def status_inquiry status.to_s.inquiry end # Update default data def update_defaults(status_key) raise "cannot call #update_defaults when status is accessed from outside the job" if @job.is_a?(String) payload = {} payload[:status] = status_key if @defaults.include?(:status) payload[:serialized_job] = @job.serialize if @defaults.include?(:serialized_job) update(payload, force: true) end def catch_exception(e) raise "cannot call #catch_exception when status is accessed from outside the job" if @job.is_a?(String) payload = {} payload[:status] = :failed if @defaults.include?(:status) payload[:serialized_job] = @job.serialize if @defaults.include?(:serialized_job) if @defaults.include?(:exception) message = e.message message = e.original_message if e.respond_to?(:original_message) payload[:exception] = {class: e.class.name, message: message} end update(payload, force: true) end end end end
ruby
MIT
e0ff3934073a9caa47a5f20261ed3bd5e6a3fc84
2026-01-04T17:45:06.564606Z
false
inkstak/activejob-status
https://github.com/inkstak/activejob-status/blob/e0ff3934073a9caa47a5f20261ed3bd5e6a3fc84/lib/activejob-status/progress.rb
lib/activejob-status/progress.rb
# frozen_string_literal: true module ActiveJob module Status class Progress attr_reader :job, :total, :progress delegate :[], :to_s, :to_json, :inspect, to: :to_h delegate :status, to: :job, prefix: true def initialize(job) @job = job @total = 100 @progress = 0 end def total=(num) @total = num job_status.update(to_h, force: true) end def progress=(num) @progress = num job_status.update(to_h, force: true) end def increment(num = 1) @progress += num job_status.update(to_h) self end def decrement(num = 1) @progress -= num job_status.update(to_h) self end def finish @progress = @total job_status.update(to_h, force: true) self end def to_h {progress: @progress, total: @total} end end end end
ruby
MIT
e0ff3934073a9caa47a5f20261ed3bd5e6a3fc84
2026-01-04T17:45:06.564606Z
false
ruby-grape/grape-rabl
https://github.com/ruby-grape/grape-rabl/blob/b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd/spec/grape_rabl_configuration.rb
spec/grape_rabl_configuration.rb
require 'spec_helper' describe 'Grape::Rabl configuration' do context 'configuration' do it 'returns default values' do expect(Grape::Rabl.configuration.cache_template_loading).to eq(false) end it 'should set and reset configuration' do Grape::Rabl.configure do |config| config.cache_template_loading = true end expect(Grape::Rabl.configuration.cache_template_loading).to eq(true) Grape::Rabl.reset_configuration! expect(Grape::Rabl.configuration.cache_template_loading).to eq(false) end end end
ruby
MIT
b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd
2026-01-04T17:45:06.741110Z
false
ruby-grape/grape-rabl
https://github.com/ruby-grape/grape-rabl/blob/b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd/spec/grape_rabl_layout_spec.rb
spec/grape_rabl_layout_spec.rb
require 'spec_helper' describe 'Grape::Rabl layout' do let(:parsed_response) { JSON.parse(last_response.body) } subject do Class.new(Grape::API) end before do subject.format :json subject.formatter :json, Grape::Formatter::Rabl subject.before do env['api.tilt.root'] = "#{File.dirname(__FILE__)}/views/layout_test" end end def app subject end context 'default' do it 'proper render with default layout' do subject.get('/about', rabl: 'user') do @user = OpenStruct.new(name: 'LTe') @project = OpenStruct.new(name: 'First') @status = 200 end get('/about') expect(parsed_response).to eq( JSON.parse(%({"status":200,"result":{"user":{"name":"LTe","project":{"name":"First"}}}})) ) end end context 'tilt layout is setup' do before do subject.before { env['api.tilt.layout'] = 'layouts/another' } end it 'proper render with specified layout' do subject.get('/about', rabl: 'user') do @user = OpenStruct.new(name: 'LTe') @project = OpenStruct.new(name: 'First') @status = 200 end get('/about') puts last_response.body expect(parsed_response).to eq( JSON.parse(%({"result":{"user":{"name":"LTe","project":{"name":"First"}}}})) ) end end context 'layout cache' do before do @views_dir = FileUtils.mkdir_p("#{File.expand_path('..', File.dirname(__FILE__))}/tmp")[0] @layout = "#{@views_dir}/layouts/application.rabl" FileUtils.cp_r("#{File.dirname(__FILE__)}/views/layout_test/.", @views_dir) subject.before { env['api.tilt.root'] = "#{File.expand_path('..', File.dirname(__FILE__))}/tmp" } subject.get('/home', rabl: 'user') do @user = OpenStruct.new(name: 'LTe', email: 'email@example.com') @project = OpenStruct.new(name: 'First') @status = 200 end end after do Grape::Rabl.reset_configuration! FileUtils.rm_f(@views_dir) end it 'should serve from cache if cache_template_loading' do Grape::Rabl.configure do |config| config.cache_template_loading = true end get '/home' expect(last_response.status).to eq(200) old_response = last_response.body open(@layout, 'a') { |f| f << 'node(:test) { "test" }' } get '/home' expect(last_response.status).to eq(200) new_response = last_response.body expect(old_response).to eq(new_response) end it 'should serve new template if cache_template_loading' do get '/home' expect(last_response.status).to eq(200) old_response = last_response.body open(@layout, 'a') { |f| f << 'node(:test) { "test" }' } get '/home' expect(last_response.status).to eq(200) new_response = last_response.body expect(old_response).not_to eq(new_response) end end end
ruby
MIT
b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd
2026-01-04T17:45:06.741110Z
false
ruby-grape/grape-rabl
https://github.com/ruby-grape/grape-rabl/blob/b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd/spec/grape_rabl_partials_spec.rb
spec/grape_rabl_partials_spec.rb
require 'spec_helper' describe 'Grape::Rabl partials' do let(:parsed_response) { JSON.parse(last_response.body) } subject do Class.new(Grape::API) end before do subject.format :json subject.formatter :json, Grape::Formatter::Rabl subject.before { env['api.tilt.root'] = "#{File.dirname(__FILE__)}/views" } end def app subject end it 'proper render partials' do subject.get('/home', rabl: 'project') do @author = OpenStruct.new(author: 'LTe') @type = OpenStruct.new(type: 'paper') @project = OpenStruct.new(name: 'First', type: @type, author: @author) end get('/home') expect(parsed_response).to eq( JSON.parse('{"project":{"name":"First","info":{"type":"paper"},"author":{"author":"LTe"}}}') ) end end
ruby
MIT
b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd
2026-01-04T17:45:06.741110Z
false
ruby-grape/grape-rabl
https://github.com/ruby-grape/grape-rabl/blob/b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd/spec/grape_rabl_spec.rb
spec/grape_rabl_spec.rb
require 'spec_helper' describe Grape::Rabl do subject do Class.new(Grape::API) end before do subject.default_format :json subject.formatter :json, Grape::Formatter::Rabl subject.formatter :xml, Grape::Formatter::Rabl subject.helpers MyHelper end def app subject end it 'should work without rabl template' do subject.get('/home') { 'Hello World' } get '/home' expect(last_response.body).to eq('"Hello World"') end it 'should raise error about root directory' do begin subject.get('/home', rabl: true) {} get '/home' rescue Exception => e expect(e.message).to include "Use Rack::Config to set 'api.tilt.root' in config.ru" end end context 'titl root is setup' do let(:parsed_response) { JSON.parse(last_response.body) } before do subject.before { env['api.tilt.root'] = "#{File.dirname(__FILE__)}/views" } end describe 'helpers' do it 'should execute helper' do subject.get('/home', rabl: 'helper') { @user = OpenStruct.new } get '/home' expect(parsed_response).to eq(JSON.parse('{"user":{"helper":"my_helper"}}')) end end describe '#render' do before do subject.get('/home', rabl: 'user') do @user = OpenStruct.new(name: 'LTe') render rabl: 'admin' end subject.get('/admin/:id', rabl: 'user') do @user = OpenStruct.new(name: 'LTe') render rabl: 'admin' if params[:id] == '1' end subject.get('/home-detail', rabl: 'user') do @user = OpenStruct.new(name: 'LTe') render rabl: 'admin', locals: { details: 'amazing detail' } end subject.get('/about', rabl: 'user') do @user = OpenStruct.new(name: 'LTe') end subject.get('/about-detail', rabl: 'user') do @user = OpenStruct.new(name: 'LTe') render locals: { details: 'just a user' } end end it 'renders template passed as argument to render method' do get('/home') expect(parsed_response).to eq(JSON.parse('{"admin":{"name":"LTe"}}')) end it 'renders admin template' do get('/admin/1') expect(parsed_response).to eq(JSON.parse('{"admin":{"name":"LTe"}}')) end it 'renders user template' do get('/admin/2') expect(parsed_response).to eq(JSON.parse('{"user":{"name":"LTe","project":null}}')) end it 'renders template passed as argument to render method with locals' do get('/home-detail') expect(parsed_response).to eq(JSON.parse('{"admin":{"name":"LTe","details":"amazing detail"}}')) end it 'renders with locals without overriding template' do get('/about-detail') expect(parsed_response).to eq(JSON.parse('{"user":{"name":"LTe","details":"just a user","project":null}}')) end it 'does not save rabl options after called #render method' do get('/home') get('/about') expect(parsed_response).to eq(JSON.parse('{"user":{"name":"LTe","project":null}}')) end it 'does not modify endpoint options' do get '/home' expect(last_request.env['api.endpoint'].options[:route_options][:rabl]).to eq 'user' end end it 'should respond with proper content-type' do subject.get('/home', rabl: 'user') {} get('/home') expect(last_response.headers['Content-Type']).to eq('application/json') end it 'should not raise error about root directory' do subject.get('/home', rabl: 'user') {} get '/home' expect(last_response.status).to eq 200 expect(last_response.body).not_to include "Use Rack::Config to set 'api.tilt.root' in config.ru" end ['user', 'user.rabl'].each do |rabl_option| it "should render rabl template (#{rabl_option})" do subject.get('/home', rabl: rabl_option) do @user = OpenStruct.new(name: 'LTe', email: 'email@example.com') @project = OpenStruct.new(name: 'First') end get '/home' expect(parsed_response).to eq(JSON.parse('{"user":{"name":"LTe","email":"email@example.com","project":{"name":"First"}}}')) end end describe 'template cache' do before do @views_dir = FileUtils.mkdir_p("#{File.expand_path('..', File.dirname(__FILE__))}/tmp")[0] @template = "#{@views_dir}/user.rabl" FileUtils.cp("#{File.dirname(__FILE__)}/views/user.rabl", @template) subject.before { env['api.tilt.root'] = "#{File.expand_path('..', File.dirname(__FILE__))}/tmp" } subject.get('/home', rabl: 'user') do @user = OpenStruct.new(name: 'LTe', email: 'email@example.com') @project = OpenStruct.new(name: 'First') end end after do Grape::Rabl.reset_configuration! FileUtils.rm_r(@views_dir) end it 'should serve from cache if cache_template_loading' do Grape::Rabl.configure do |config| config.cache_template_loading = true end get '/home' expect(last_response.status).to eq(200) old_response = last_response.body open(@template, 'a') { |f| f << 'node(:test) { "test" }' } get '/home' expect(last_response.status).to eq(200) new_response = last_response.body expect(old_response).to eq(new_response) end it 'should maintain different cached templates for different formats' do Grape::Rabl.configure do |config| config.cache_template_loading = true end get '/home' expect(last_response.status).to eq(200) json_response = last_response.body get '/home.xml' expect(last_response.status).to eq(200) xml_response = last_response.body expect(json_response).not_to eq(xml_response) open(@template, 'a') { |f| f << 'node(:test) { "test" }' } get '/home.xml' expect(last_response.status).to eq(200) expect(last_response.body).to eq(xml_response) get '/home.json' expect(last_response.status).to eq(200) expect(last_response.body).to eq(json_response) end it 'should serve new template unless cache_template_loading' do get '/home' expect(last_response.status).to eq(200) old_response = last_response.body open(@template, 'a') { |f| f << 'node(:test) { "test" }' } get '/home' expect(last_response.status).to eq(200) new_response = last_response.body expect(old_response).not_to eq(new_response) end end end end
ruby
MIT
b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd
2026-01-04T17:45:06.741110Z
false
ruby-grape/grape-rabl
https://github.com/ruby-grape/grape-rabl/blob/b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd/spec/grape_rabl_formatter_spec.rb
spec/grape_rabl_formatter_spec.rb
require 'spec_helper' describe 'Grape::Rabl formatter' do subject do Class.new(Grape::API) end let(:xml_render) do %(<?xml version="1.0" encoding="UTF-8"?> <hash> <errors type="array"> <error>bad</error> <error>things</error> <error>happened</error> </errors> </hash> ) end def app subject end context 'rendering' do context 'when no rabl template is specified' do before do # Grape::API defaults to the following declarations: # content_type :xml, 'application/xml' # content_type :json, 'application/json' # content_type :binary, 'application/octet-stream' # content_type :txt, 'text/plain' # default_format :txt subject.formatter :xml, Grape::Formatter::Rabl subject.formatter :txt, Grape::Formatter::Rabl subject.get('/oops') { { errors: %w[bad things happened] } } expect_any_instance_of(Grape::Rabl::Formatter).to receive(:render).and_call_original end it 'falls back to :txt given no other format information' do get '/oops' expect(last_response.body).to eq('{:errors=>["bad", "things", "happened"]}') expect(last_response.headers['Content-Type']).to eq('text/plain') end it 'falls back to the file extension if it is a valid format' do get '/oops.xml' expect(last_response.body).to eq(xml_render) expect(last_response.headers['Content-Type']).to eq('application/xml') end it 'falls back to the value of the `format` parameter in the query string if it is provided' do get '/oops?format=xml' expect(last_response.body).to eq(xml_render) expect(last_response.headers['Content-Type']).to eq('application/xml') end it 'falls back to the format set by the `format` option if it is a valid format' do # `format` option must be declared before endpoint subject.format :xml subject.get('/oops/2') { { errors: %w[bad things happened] } } get '/oops/2' expect(last_response.body).to eq(xml_render) expect(last_response.headers['Content-Type']).to eq('application/xml') end it 'falls back to the `Accept` header if it is a valid format' do get '/oops', {}, 'HTTP_ACCEPT' => 'application/xml' expect(last_response.body).to eq(xml_render) expect(last_response.headers['Content-Type']).to eq('application/xml') end it 'falls back to the default_format option if it is a valid format' do # `default_format` option must be declared before endpoint subject.default_format :xml subject.get('/oops/2') { { errors: %w[bad things happened] } } get '/oops/2' expect(last_response.body).to eq(xml_render) expect(last_response.headers['Content-Type']).to eq('application/xml') end end end end
ruby
MIT
b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd
2026-01-04T17:45:06.741110Z
false
ruby-grape/grape-rabl
https://github.com/ruby-grape/grape-rabl/blob/b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd/spec/grape_rabl_xml_spec.rb
spec/grape_rabl_xml_spec.rb
require 'spec_helper' describe Grape::Rabl do subject do Class.new(Grape::API) end before do subject.format :xml subject.formatter :xml, Grape::Formatter::Rabl end def app subject end context 'with xml format' do before do subject.before do env['api.tilt.root'] = "#{File.dirname(__FILE__)}/views" env['api.format'] = :xml end end it 'should respond with proper content-type' do subject.get('/home', rabl: 'user') {} get('/home') expect(last_response.headers['Content-Type']).to eq('application/xml') end ['user', 'user.rabl'].each do |rabl_option| it "should render rabl template (#{rabl_option})" do subject.get('/home', rabl: rabl_option) do @user = OpenStruct.new(name: 'LTe', email: 'email@example.com') @project = OpenStruct.new(name: 'First') end get '/home' expect(last_response.body).to eq(%(<?xml version="1.0" encoding="UTF-8"?> <user> <name>LTe</name> <email>email@example.com</email> <project> <name>First</name> </project> </user> )) end end end end
ruby
MIT
b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd
2026-01-04T17:45:06.741110Z
false
ruby-grape/grape-rabl
https://github.com/ruby-grape/grape-rabl/blob/b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd/spec/spec_helper.rb
spec/spec_helper.rb
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__)) require 'bundler' Bundler.setup :default, :test require 'coveralls' Coveralls.wear! require 'active_support/core_ext/hash/conversions' require 'grape/rabl' require 'rspec' require 'rack/test' require 'ostruct' RSpec.configure do |config| config.include Rack::Test::Methods config.raise_errors_for_deprecations! end Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
ruby
MIT
b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd
2026-01-04T17:45:06.741110Z
false
ruby-grape/grape-rabl
https://github.com/ruby-grape/grape-rabl/blob/b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd/spec/support/my_helper.rb
spec/support/my_helper.rb
module MyHelper def my_helper 'my_helper' end end
ruby
MIT
b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd
2026-01-04T17:45:06.741110Z
false
ruby-grape/grape-rabl
https://github.com/ruby-grape/grape-rabl/blob/b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd/lib/grape-rabl.rb
lib/grape-rabl.rb
require 'rabl' require 'grape' require 'grape/rabl' require 'grape-rabl/tilt' require 'grape-rabl/version' require 'grape-rabl/formatter' require 'grape-rabl/render' require 'grape-rabl/configuration' module Grape module Rabl class << self def configure yield(configuration) configuration end def configuration @configuration ||= Configuration.new end def reset_configuration! @configuration = nil end end end end
ruby
MIT
b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd
2026-01-04T17:45:06.741110Z
false
ruby-grape/grape-rabl
https://github.com/ruby-grape/grape-rabl/blob/b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd/lib/grape/rabl.rb
lib/grape/rabl.rb
require 'grape-rabl' module Grape module Formatter module Rabl class << self def call(object, env) Grape::Rabl::Formatter.new(object, env).render end end end end end
ruby
MIT
b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd
2026-01-04T17:45:06.741110Z
false
ruby-grape/grape-rabl
https://github.com/ruby-grape/grape-rabl/blob/b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd/lib/grape-rabl/tilt.rb
lib/grape-rabl/tilt.rb
require 'tilt' Rabl.register!
ruby
MIT
b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd
2026-01-04T17:45:06.741110Z
false
ruby-grape/grape-rabl
https://github.com/ruby-grape/grape-rabl/blob/b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd/lib/grape-rabl/version.rb
lib/grape-rabl/version.rb
module Grape module Rabl VERSION = '0.5.0'.freeze end end
ruby
MIT
b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd
2026-01-04T17:45:06.741110Z
false
ruby-grape/grape-rabl
https://github.com/ruby-grape/grape-rabl/blob/b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd/lib/grape-rabl/render.rb
lib/grape-rabl/render.rb
module Grape module Rabl module Render def render(options = {}) env['api.tilt.rabl'] = options[:rabl] env['api.tilt.rabl_locals'] = options[:locals] end end end end Grape::Endpoint.send(:include, Grape::Rabl::Render)
ruby
MIT
b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd
2026-01-04T17:45:06.741110Z
false
ruby-grape/grape-rabl
https://github.com/ruby-grape/grape-rabl/blob/b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd/lib/grape-rabl/configuration.rb
lib/grape-rabl/configuration.rb
module Grape module Rabl class Configuration attr_accessor :cache_template_loading def initialize @cache_template_loading = false end end end end
ruby
MIT
b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd
2026-01-04T17:45:06.741110Z
false
ruby-grape/grape-rabl
https://github.com/ruby-grape/grape-rabl/blob/b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd/lib/grape-rabl/formatter.rb
lib/grape-rabl/formatter.rb
require 'json' module Grape module Rabl class Formatter class << self def tilt_cache @tilt_cache ||= ::Tilt::Cache.new end end attr_reader :env, :endpoint, :object def initialize(object, env) @env = env @endpoint = env['api.endpoint'] @object = object end def render if rablable? rabl do |template| engine = tilt_template(template) output = engine.render endpoint, locals if layout_template layout_template.render(endpoint) { output } else output end end else fallback_formatter.call object, env end end private # Find a formatter to fallback to. `env[Grape::Env::API_FORMAT]` will always be a # valid formatter, otherwise a HTTP 406 error would have already have been thrown def fallback_formatter Grape::Formatter.formatter_for(env[Grape::Env::API_FORMAT]) end def view_path(template) if template.split('.')[-1] == 'rabl' File.join(env['api.tilt.root'], template) else File.join(env['api.tilt.root'], (template + '.rabl')) end end def rablable? !!rabl_template end def rabl raise 'missing rabl template' unless rabl_template set_view_root unless env['api.tilt.root'] yield rabl_template end def locals env['api.tilt.rabl_locals'] || endpoint.options[:route_options][:rabl_locals] || {} end def rabl_template env['api.tilt.rabl'] || endpoint.options[:route_options][:rabl] end def set_view_root raise "Use Rack::Config to set 'api.tilt.root' in config.ru" end def tilt_template(template) if Grape::Rabl.configuration.cache_template_loading Grape::Rabl::Formatter.tilt_cache.fetch(tilt_cache_key(template)) { ::Tilt.new(view_path(template), tilt_options) } else ::Tilt.new(view_path(template), tilt_options) end end def tilt_options { format: env['api.format'], view_path: env['api.tilt.root'] } end def layout_template layout_path = view_path(env['api.tilt.layout'] || 'layouts/application') if Grape::Rabl.configuration.cache_template_loading Grape::Rabl::Formatter.tilt_cache.fetch(tilt_cache_key(layout_path)) { ::Tilt.new(layout_path, tilt_options) if File.exist?(layout_path) } else ::Tilt.new(layout_path, tilt_options) if File.exist?(layout_path) end end def tilt_cache_key(path) Digest::MD5.hexdigest("#{path}#{tilt_options}") end end end end
ruby
MIT
b201ebdb0dc44906e5b42619f060fa3ac4e5bdfd
2026-01-04T17:45:06.741110Z
false
joliss/markdown-rails
https://github.com/joliss/markdown-rails/blob/bc43c1c110b66f92481ad3733e0fb6495c846d7b/testapp/app/helpers/application_helper.rb
testapp/app/helpers/application_helper.rb
module ApplicationHelper end
ruby
MIT
bc43c1c110b66f92481ad3733e0fb6495c846d7b
2026-01-04T17:45:12.101166Z
false
joliss/markdown-rails
https://github.com/joliss/markdown-rails/blob/bc43c1c110b66f92481ad3733e0fb6495c846d7b/testapp/app/helpers/home_helper.rb
testapp/app/helpers/home_helper.rb
module HomeHelper end
ruby
MIT
bc43c1c110b66f92481ad3733e0fb6495c846d7b
2026-01-04T17:45:12.101166Z
false
joliss/markdown-rails
https://github.com/joliss/markdown-rails/blob/bc43c1c110b66f92481ad3733e0fb6495c846d7b/testapp/app/controllers/home_controller.rb
testapp/app/controllers/home_controller.rb
class HomeController < ApplicationController def index end end
ruby
MIT
bc43c1c110b66f92481ad3733e0fb6495c846d7b
2026-01-04T17:45:12.101166Z
false
joliss/markdown-rails
https://github.com/joliss/markdown-rails/blob/bc43c1c110b66f92481ad3733e0fb6495c846d7b/testapp/app/controllers/application_controller.rb
testapp/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base protect_from_forgery end
ruby
MIT
bc43c1c110b66f92481ad3733e0fb6495c846d7b
2026-01-04T17:45:12.101166Z
false
joliss/markdown-rails
https://github.com/joliss/markdown-rails/blob/bc43c1c110b66f92481ad3733e0fb6495c846d7b/testapp/db/seeds.rb
testapp/db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first)
ruby
MIT
bc43c1c110b66f92481ad3733e0fb6495c846d7b
2026-01-04T17:45:12.101166Z
false
joliss/markdown-rails
https://github.com/joliss/markdown-rails/blob/bc43c1c110b66f92481ad3733e0fb6495c846d7b/testapp/test/test_helper.rb
testapp/test/test_helper.rb
ENV["RAILS_ENV"] = "test" require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' class ActiveSupport::TestCase # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order. # # Note: You'll currently still have to declare fixtures explicitly in integration tests # -- they do not yet inherit this setting fixtures :all # Add more helper methods to be used by all tests here... end
ruby
MIT
bc43c1c110b66f92481ad3733e0fb6495c846d7b
2026-01-04T17:45:12.101166Z
false
joliss/markdown-rails
https://github.com/joliss/markdown-rails/blob/bc43c1c110b66f92481ad3733e0fb6495c846d7b/testapp/test/performance/browsing_test.rb
testapp/test/performance/browsing_test.rb
require 'test_helper' require 'rails/performance_test_help' class BrowsingTest < ActionDispatch::PerformanceTest # Refer to the documentation for all available options # self.profile_options = { :runs => 5, :metrics => [:wall_time, :memory] # :output => 'tmp/performance', :formats => [:flat] } def test_homepage get '/' end end
ruby
MIT
bc43c1c110b66f92481ad3733e0fb6495c846d7b
2026-01-04T17:45:12.101166Z
false
joliss/markdown-rails
https://github.com/joliss/markdown-rails/blob/bc43c1c110b66f92481ad3733e0fb6495c846d7b/testapp/test/unit/helpers/home_helper_test.rb
testapp/test/unit/helpers/home_helper_test.rb
require 'test_helper' class HomeHelperTest < ActionView::TestCase end
ruby
MIT
bc43c1c110b66f92481ad3733e0fb6495c846d7b
2026-01-04T17:45:12.101166Z
false
joliss/markdown-rails
https://github.com/joliss/markdown-rails/blob/bc43c1c110b66f92481ad3733e0fb6495c846d7b/testapp/test/functional/home_controller_test.rb
testapp/test/functional/home_controller_test.rb
require 'test_helper' class HomeControllerTest < ActionController::TestCase test "should get index" do get :index assert_response :success end end
ruby
MIT
bc43c1c110b66f92481ad3733e0fb6495c846d7b
2026-01-04T17:45:12.101166Z
false
joliss/markdown-rails
https://github.com/joliss/markdown-rails/blob/bc43c1c110b66f92481ad3733e0fb6495c846d7b/testapp/config/application.rb
testapp/config/application.rb
require File.expand_path('../boot', __FILE__) require 'rails/all' if defined?(Bundler) # If you precompile assets before deploying to production, use this line Bundler.require(*Rails.groups(:assets => %w(development test))) # If you want your assets lazily compiled in production, use this line # Bundler.require(:default, :assets, Rails.env) end module Testapp class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Custom directories with classes and modules you want to be autoloadable. # config.autoload_paths += %W(#{config.root}/extras) # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named. # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Activate observers that should always be running. # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] # Use SQL instead of Active Record's schema dumper when creating the database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Enforce whitelist mode for mass assignment. # This will create an empty whitelist of attributes available for mass-assignment for all models # in your app. As such, your models will need to explicitly whitelist or blacklist accessible # parameters by using an attr_accessible or attr_protected declaration. # config.active_record.whitelist_attributes = true # Enable the asset pipeline config.assets.enabled = true # Version of your assets, change this if you want to expire all your assets config.assets.version = '1.0' end end
ruby
MIT
bc43c1c110b66f92481ad3733e0fb6495c846d7b
2026-01-04T17:45:12.101166Z
false
joliss/markdown-rails
https://github.com/joliss/markdown-rails/blob/bc43c1c110b66f92481ad3733e0fb6495c846d7b/testapp/config/environment.rb
testapp/config/environment.rb
# Load the rails application require File.expand_path('../application', __FILE__) # Initialize the rails application Testapp::Application.initialize!
ruby
MIT
bc43c1c110b66f92481ad3733e0fb6495c846d7b
2026-01-04T17:45:12.101166Z
false
joliss/markdown-rails
https://github.com/joliss/markdown-rails/blob/bc43c1c110b66f92481ad3733e0fb6495c846d7b/testapp/config/routes.rb
testapp/config/routes.rb
Testapp::Application.routes.draw do root :to => "home#index" get 'partial' => 'home#partial' # The priority is based upon order of creation: # first created -> highest priority. # Sample of regular route: # match 'products/:id' => 'catalog#view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # resources :products # Sample resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Sample resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Sample resource route with more complex sub-resources # resources :products do # resources :comments # resources :sales do # get 'recent', :on => :collection # end # end # Sample resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end # You can have the root of your site routed with "root" # just remember to delete public/index.html. # root :to => 'welcome#index' # See how all your routes lay out with "rake routes" # This is a legacy wild controller route that's not recommended for RESTful applications. # Note: This route will make all actions in every controller accessible via GET requests. # match ':controller(/:action(/:id))(.:format)' end
ruby
MIT
bc43c1c110b66f92481ad3733e0fb6495c846d7b
2026-01-04T17:45:12.101166Z
false
joliss/markdown-rails
https://github.com/joliss/markdown-rails/blob/bc43c1c110b66f92481ad3733e0fb6495c846d7b/testapp/config/boot.rb
testapp/config/boot.rb
require 'rubygems' # Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
ruby
MIT
bc43c1c110b66f92481ad3733e0fb6495c846d7b
2026-01-04T17:45:12.101166Z
false
joliss/markdown-rails
https://github.com/joliss/markdown-rails/blob/bc43c1c110b66f92481ad3733e0fb6495c846d7b/testapp/config/initializers/session_store.rb
testapp/config/initializers/session_store.rb
# Be sure to restart your server when you modify this file. Testapp::Application.config.session_store :cookie_store, key: '_testapp_session' # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rails generate session_migration") # Testapp::Application.config.session_store :active_record_store
ruby
MIT
bc43c1c110b66f92481ad3733e0fb6495c846d7b
2026-01-04T17:45:12.101166Z
false
joliss/markdown-rails
https://github.com/joliss/markdown-rails/blob/bc43c1c110b66f92481ad3733e0fb6495c846d7b/testapp/config/initializers/wrap_parameters.rb
testapp/config/initializers/wrap_parameters.rb
# Be sure to restart your server when you modify this file. # # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:json] end # Disable root element in JSON by default. ActiveSupport.on_load(:active_record) do self.include_root_in_json = false end
ruby
MIT
bc43c1c110b66f92481ad3733e0fb6495c846d7b
2026-01-04T17:45:12.101166Z
false
joliss/markdown-rails
https://github.com/joliss/markdown-rails/blob/bc43c1c110b66f92481ad3733e0fb6495c846d7b/testapp/config/initializers/inflections.rb
testapp/config/initializers/inflections.rb
# Be sure to restart your server when you modify this file. # Add new inflection rules using the following format # (all these examples are active by default): # ActiveSupport::Inflector.inflections do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', 'people' # inflect.uncountable %w( fish sheep ) # end # # These inflection rules are supported but not enabled by default: # ActiveSupport::Inflector.inflections do |inflect| # inflect.acronym 'RESTful' # end
ruby
MIT
bc43c1c110b66f92481ad3733e0fb6495c846d7b
2026-01-04T17:45:12.101166Z
false
joliss/markdown-rails
https://github.com/joliss/markdown-rails/blob/bc43c1c110b66f92481ad3733e0fb6495c846d7b/testapp/config/initializers/backtrace_silencers.rb
testapp/config/initializers/backtrace_silencers.rb
# Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. # Rails.backtrace_cleaner.remove_silencers!
ruby
MIT
bc43c1c110b66f92481ad3733e0fb6495c846d7b
2026-01-04T17:45:12.101166Z
false