repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
Marketcircle/Specs
|
AVAnimator/2.0.0/AVAnimator.podspec
|
#
Pod::Spec.new do |s|
s.name = "AVAnimator"
s.version = "2.0.0"
s.summary = "VAnimator is an iOS library that makes it easy to implement non-trivial animated/video content in iOS."
s.homepage = "http://www.modejong.com/AVAnimator/index.html"
s.license = { :type => 'LGPL', :file => 'License.txt' }
s.author = { "<NAME>" => "<EMAIL>" }
s.source = { :git => "https://github.com/mdejong/AVAnimator.git", :tag => "AVAnimator-2.0.0" }
s.platform = :ios, '5.0'
s.source_files = 'Classes', 'Classes/**/*.{h,m,c}'
s.exclude_files = 'Classes/Tests'
s.frameworks = 'QuartzCore', 'AVFoundation', 'AudioToolbox', 'CoreVideo', 'CoreMedia', 'MediaPlayer'
s.library = 'z'
s.requires_arc = false
s.subspec 'ASM' do |asm|
asm.source_files = 'Classes/**/*.{s}'
asm.compiler_flags = '-no-integrated-as'
end
end
|
Marketcircle/Specs
|
MotionJpegImageView/0.0.1/MotionJpegImageView.podspec
|
Pod::Spec.new do |s|
s.name = "MotionJpegImageView"
s.version = "0.0.1"
s.summary = "MotionJpegImageView lets you display MJPEG streams on iOS. Typically 7 to 8 times faster than using UIView."
s.description = <<-DESC
MotionJpegImageView creates a connection to the stream
and receives JPEG frames one at a time over the network.
It turns out this approach is typically seven or eight
times faster than using UIWebView to render MJPEG
streams.
Just provide a URL for the video stream and you're good.
Internally, MotionJpegImageView achieves better
performance by avoiding overheads of parsing and
rendering each frame as if it were a web page which
UIView does.
Internally, MotionJpegImageView creates a connection to
the stream and receives frames one at a time over the
network. As it receives each frame, it hydrates the
stream data into a UIImage object, and then sets its
inherited image property. Thus the only bottlenecks
to getting high framerates are:
1. The speed of your network connection
2. The frame rate of the IP camera
3. The phone’s ability to process inbound packets and
rehydrate UIImage files from raw JPEG data.
DESC
s.homepage = "http://thinkflood.com/support/redeye/software/open-source-software/motion-jpeg-image-view-ios/http://EXAMPLE/Motion-JPEG-Image-View-for-iOS"
s.license = {
:type => 'MIT',
:text => <<-LICENSE
Created by <NAME> on 10/3/11.
Copyright 2011 ThinkFlood Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
LICENSE
}
s.author = { "<NAME>" => "<EMAIL>" }
s.source = { :git => "https://github.com/mateagar/Motion-JPEG-Image-View-for-iOS.git", :commit => "<PASSWORD>" }
s.source_files = 'MotionJpegImageView/MotionJpegImageView.{h,mm}'
s.framework = 'UIKit'
s.requires_arc = false
s.platform = :ios
end
|
Marketcircle/Specs
|
CZDateFormatterCache/1.1.1/CZDateFormatterCache.podspec
|
<gh_stars>1-10
Pod::Spec.new do |s|
s.name = "CZDateFormatterCache"
s.version = "1.1.1"
s.summary = "A shared NSDateFormatter cache to improve scrolling performance in UITableViewCells."
s.homepage = "https://github.com/carezone/CZDateFormatterCache"
s.license = "Apache 2.0"
s.authors = { "<NAME>" => "<EMAIL>", "<NAME>" => "<EMAIL>" }
s.source = { :git => "https://github.com/carezone/CZDateFormatterCache.git", :tag => "1.1.1" }
s.platform = :ios, '5.0'
s.source_files = 'CZDateFormatterCache'
s.requires_arc = true
end
|
Marketcircle/Specs
|
AFProgressiveImageDownload/0.1/AFProgressiveImageDownload.podspec
|
#
# Be sure to run `pod spec lint AFProgressiveImageDownload.podspec' to ensure this is a
# valid spec and remove all comments before submitting the spec.
#
# To learn more about the attributes see http://docs.cocoapods.org/specification.html
#
Pod::Spec.new do |s|
s.name = "AFProgressiveImageDownload"
s.version = "0.1"
s.summary = "A category on UIView that allows you to progressively download images providing seamless enhancement."
s.homepage = "http://github.com/subdigital/AFProgressiveImageDownload"
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { "<NAME>" => "<EMAIL>" }
s.source = { :git => "https://github.com/subdigital/AFProgressiveImageDownload.git", :tag => "0.1" }
s.platform = :ios, '6.0'
s.source_files = 'AFProgressiveImageDownload/**/*.{h,m}'
s.requires_arc = true
s.dependency 'AFNetworking', '~> 1.0'
end
|
Marketcircle/Specs
|
fullcontact-objc/1.0.0/fullcontact-objc.podspec
|
Pod::Spec.new do |s|
s.name = "fullcontact-objc"
s.version = "1.0.0"
s.license = { :type => 'Apache License Version 2.0', :file => 'LICENSE' }
s.summary = "Objective-C library to access FullContact's v2 API endpoints via iOS and Mac OS X."
s.homepage = "https://github.com/fullcontact/fullcontact-objc"
s.author = { "<NAME>" => "<EMAIL>" }
s.source = { :git => "https://github.com/fullcontact/fullcontact-objc.git", :tag => "1.0.0" }
s.source_files = 'fullcontact-objc/fullcontact-objc/Classes/**/*.{h,m}'
s.ios.deployment_target = '5.0'
s.osx.deployment_target = '10.7'
s.frameworks = 'SystemConfiguration', 'UIKit', 'MobileCoreServices', 'Foundation'
s.requires_arc = true
s.dependency 'AFNetworking'
end
|
Marketcircle/Specs
|
ParseKit/0.7/ParseKit.podspec
|
<reponame>Marketcircle/Specs
Pod::Spec.new do |s|
s.name = 'ParseKit'
s.version = '0.7'
s.license = 'Apache'
s.summary = 'Objective-C/Cocoa String Tokenizer and Parser toolkit. Supports Grammars.'
s.homepage = 'http://parsekit.com/'
s.author = { '<NAME>' => '<EMAIL>' }
s.source = { :git => 'https://github.com/itod/parsekit.git', :tag => '0.7'}
s.description = %{
ParseKit is a Mac OS X Framework written by <NAME> in
Objective-C 2.0 and released under the Apache Open Source License
Version 2.0. ParseKit is suitable for use on Mac OS X Leopard,
Snow Leopard or iOS. ParseKit is an Objective-C implementation
of the tools described in Building Parsers with Java by Steven
<NAME>.
ParseKit includes additional features beyond the
designs from the book and also some changes to match common
Cocoa/Objective-C conventions. These changes are relatively superficial,
however, and Metsker’s book is the best documentation available
for ParseKit.
}
s.source_files = 'include/**/*.{h,m}', 'src/**/*.{h,m}'
s.ios.exclude_files = 'src/PKSParserGenVisitor.{h,m}'
s.osx.source_files = 'lib/MGTemplateEngine/*.{h,m}'
s.osx.exclude_files = 'lib/MGTemplateEngine/RegexKitTemplateMatcher.{h,m}'
s.ios.prefix_header_file = 'src/ParseKitMobile_Prefix.pch'
s.osx.prefix_header_file = 'src/ParseKit_Prefix.pch'
s.ios.frameworks = 'Foundation'
s.osx.framework = 'Foundation'
s.library = 'icucore'
s.requires_arc = false
end
|
Marketcircle/Specs
|
OLImageView/1.3.0/OLImageView.podspec
|
<gh_stars>0
Pod::Spec.new do |s|
s.name = "OLImageView"
s.version = "1.3.0"
s.summary = "Animated GIFs implemented the right way."
s.homepage = "https://www.github.com/ondalabs/OLImageView"
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { "<NAME>" => "<EMAIL>" }
s.source = { :git => "https://github.com/ondalabs/OLImageView.git", :tag => s.version.to_s }
s.platform = :ios, '5.0'
s.source_files = 'OLImage.{h,m}', 'OLImageView.{h,m}'
s.framework = 'ImageIO', 'MobileCoreServices', 'QuartzCore'
s.requires_arc = true
s.subspec 'AFNetworking' do |af|
af.dependency 'AFNetworking'
af.source_files = "Categories/AFImageRequestOperation+OLImage.{h,m}"
end
s.preferred_dependency = 'AFNetworking'
end
|
Marketcircle/Specs
|
ZXTools/1.3/ZXTools.podspec
|
<gh_stars>1-10
Pod::Spec.new do |s|
s.name = "ZXTools"
s.version = "1.3"
s.summary = "张玺的工具箱子,扩展部分UIKit和UIFoundation的类,实现更丰富的功能."
#s.license = {:type => 'BSD' }
s.license = 'MIT'
#s.license = { :type => 'MIT', :file => 'LICENSE' }
s.homepage = "https://github.com/zhangxigithub/ZXTools"
s.author = { "zhangxi" => "<EMAIL>" }
s.source = { :git => "https://github.com/zhangxigithub/ZXTools.git",:tag=>"v1.3"}
s.platform = :ios, '5.0'
s.subspec 'ZXURL' do | ssZXURL |
ssZXURL.source_files = 'Class/ZXURL/*.{h,m}'
end
s.subspec 'ZXBase64' do | ssZXBase64 |
ssZXBase64.source_files = 'Class/ZXBase64/*.{h,m}'
end
s.subspec 'ZXAES' do | ssZXAES |
ssZXAES.source_files = 'Class/ZXAES/*.{h,m}'
end
s.subspec 'ZXALAssetsLibrary' do | ssZXALAssetsLibrary |
ssZXALAssetsLibrary.source_files = 'Class/ZXALAssetsLibrary/*.{h,m}'
end
s.subspec 'ZXApplication' do | ssZXApplication |
ssZXApplication.source_files = 'Class/ZXApplication/*.{h,m}'
end
s.subspec 'ZXDES' do | ssZXDES |
ssZXDES.source_files = 'Class/ZXDES/*.{h,m}'
end
s.subspec 'ZXMD5' do | ssZXMD5 |
ssZXMD5.source_files = 'Class/ZXMD5/*.{h,m}'
end
s.subspec 'ZXString' do | ssZXString |
ssZXString.source_files = 'Class/ZXString/*.{h,m}'
end
s.subspec 'ZXTableView' do | ssZXTableView |
ssZXTableView.source_files = 'Class/ZXTableView/*.{h,m}'
end
s.subspec 'ZXMacro' do | ssZXMacro |
ssZXMacro.source_files = 'Class/ZXMacro/*.{h,m}'
end
s.subspec 'ZXDate' do | ssZXDate |
ssZXDate.source_files = 'Class/ZXDate/*.{h,m}'
end
s.ios.frameworks = 'AssetsLibrary',
'CoreLocation',
'MapKit',
'CoreGraphics',
'AVFoundation'
s.requires_arc = true
end
|
Marketcircle/Specs
|
TheAmazingAudioEngine/1.0/TheAmazingAudioEngine.podspec
|
#
# Be sure to run `pod spec lint TheAmazingAudioEngine.podspec' to ensure this is a
# valid spec and remove all comments before submitting the spec.
#
# To learn more about the attributes see http://docs.cocoapods.org/specification.html
#
Pod::Spec.new do |s|
s.name = "TheAmazingAudioEngine"
s.version = "1.0"
s.summary = "Core Audio, Cordially: A sophisticated framework for iOS audio applications, built so you don't have to."
s.homepage = "https://github.com/TheAmazingAudioEngine/TheAmazingAudioEngine"
s.license = { :type => 'zlib', :file => 'License.txt' }
s.author = { "michaeltyson" => "<EMAIL>" }
s.source = { :git => "https://github.com/TheAmazingAudioEngine/TheAmazingAudioEngine.git", :tag => "1.0" }
s.platform = :ios, '4.3'
s.source_files = 'TheAmazingAudioEngine/**/*.{h,m,c}', 'Modules/**/*.{h,m,c}'
s.frameworks = 'AudioToolbox', 'Accelerate'
s.requires_arc = false
end
|
Marketcircle/Specs
|
DTAUS/0.1.0/DTAUS.podspec
|
#
# Be sure to run `pod spec lint DTAUS.podspec' to ensure this is a
# valid spec and remove all comments before submitting the spec.
#
# To learn more about the attributes see http://docs.cocoapods.org/specification.html
#
Pod::Spec.new do |s|
s.name = "DTAUS"
s.version = "0.1.0"
s.summary = "A simple DTAUS parser written in Objective-C."
s.homepage = "https://github.com/toco/DTAUS"
s.license = 'MIT'
s.author = { "<NAME>" => "<EMAIL>" }
s.source = { :git => "https://github.com/toco/DTAUS.git", :tag => "0.1.0" }
s.ios.deployment_target = '5.0'
s.osx.deployment_target = '10.7'
s.source_files = 'DTAUS'
s.framework = 'Foundation'
s.requires_arc = true
end
|
AlessandroPTSN/heroku-buildpack-r
|
bin/copy_libs.rb
|
#!/usr/bin/env ruby
#
# utility to copy libraries (some installed via Aptfile) which are referenced by the R packages
# built during execution of init.R/packrat/renv, which need to be "packaged" into the slug since
# the chroot isn't included at runtime.
#
# this script uses ldd to inspect each .so file in the given directory to get the referenced .so
# files to copy them to /app/R/lib/R/lib so that they can be found at runtime.
#
# any dynamic dependencies, such as a command line utilities, scripts or any other files, won't be
# included in this process, as there is no definitive way to know what is needed, so YMMV.
#
require 'open3'
def find_depend_libs(binary)
cmd = "/usr/bin/ldd #{binary} | /usr/bin/awk '{print $3}' | /usr/bin/sort -u"
output = ""
res = nil
Open3.popen2e(cmd, :chdir=>"/") do |stdin, stdout_stderr, wait_thr|
output = stdout_stderr.read.chomp
res = wait_thr.value
end
raise StandardError.new("Failed to find dependent libraries for '#{binary}'. #{output}") if res&.exitstatus != 0
output.split("\n")
.reject {|s| s == "" }
.reject {|s| s =~ /^\/app/ }
.select {|s| File.exists?(s) }
.collect {|f| [f, File.basename(f)] }
end
def copy_depend_libs(path, binary)
find_depend_libs(binary).each do |src, dest|
target = File.join(path, dest)
next if File.exists?(target)
print "⦁ #{src} → #{target} "
copy_binary_file src, target
if target =~ /\.so/ && target !~ /\.so$/
Dir.chdir(File.dirname(target)) do
basename = File.basename(target)
symlinkname = basename.sub(/\.so.*/, ".so")
File.symlink(basename, symlinkname) unless File.exists?(symlinkname)
end
end
print "[OK]\n"
copy_depend_libs path, src
end
end
def copy_binary_file(src, target)
File.open(src, 'rb') do |f|
File.open(target, 'wb') do |g|
g.chmod(0777) # executable
g.write(f.read)
end
end
end
# where to search
# e.g. /app/R/site-library/**/*.so
search=ARGV[0]
puts "Searching in #{search}"
# destination for copied libs
dest_path = "/app/R/lib/R/lib"
# all related SO files
Dir.glob(search).each do |binary|
copy_depend_libs(dest_path, binary)
end
|
lzrd/parley
|
test/test_parley.rb
|
<reponame>lzrd/parley<filename>test/test_parley.rb
$LOAD_PATH.unshift("#{File.dirname(__FILE__)}/../lib") if __FILE__ == $0
$LOAD_PATH.unshift("#{File.dirname(__FILE__)}") if __FILE__ == $0
require 'helper'
require "test/unit"
require 'parley'
require 'stringio'
require 'open3'
#class TestParley < Test::Unit::TestCase
# should "probably rename this file and start testing for real" do
# flunk "hey buddy, you should probably rename this file and start testing for real"
# end
#end
class StringIO
include Parley
end
class TestIO < Test::Unit::TestCase
def setup
@text = "red apple\nbright white\nthree dogs\nblue sky\nafter glow\n"
@test_verbose = false # Set to true if you want to see conversations
end
def teardown
# no teardown required
end
def test_timeout_positive
read, write, pid = PTY.spawn('/bin/sleep 20')
result = read.parley(5, [:timeout, :timeout])
assert(result == :timeout, "** ERROR result = #{result}")
end
# Negative timeout behaves like zero since that time is already passed.
def test_negative_timeout
sleep_seconds = 5
read, write, pid = PTY.spawn("/bin/sleep #{sleep_seconds}")
start_time = Time.now
result = read.parley(-1, [:timeout, :timeout])
delta_t = Time.now - start_time
assert(result == :timeout, "** ERROR result = #{result}")
assert(delta_t < sleep_seconds/2,
"Immediate timeout did not happen: delta_t = #{delta_t}")
end
# Zero timeout results in immediate :timeout if no data available
def test_zero_timeout
sleep_seconds = 10
read, write, pid = PTY.spawn("/bin/sleep #{sleep_seconds}")
start_time = Time.now
result = read.parley(0, [:timeout, :timeout], [:eof, :eof])
end_time = Time.now
delta_t = (end_time - start_time)
assert(result == :timeout, "** ERROR result = #{result}")
assert(delta_t < (sleep_seconds/2.0),
"Test ended too late: delta_t(#{delta_t}) >= #{sleep_seconds/2.0}")
end
=begin
# This syntax is not final or implemented yet
def test_multiple_spawned_commands
total = 0
count = 0
commands1 = []
(1..5).each do |i|
# push [read, write, pid] onto commands
commands1 << PTY.spawn("sleep 3; echo N=#{i}; sleep 2")
end
pattern_action_1 = [
/N=(\d+)/, # find this pattern in output of all commands
lambda do |m, r, w|
total += m[1].to_i
count += 1
:continue; # we don't want to terminate the expect call
end
]
commands2 = []
(6..10).each do |i|
# push [read, write, pid] onto commands
commands2 << PTY.spawn("sleep 3; echo X=#{i}; sleep 2")
end
pattern_action_2 = [
/X=(\d+)/, # find this pattern in output of all commands
lambda do |m, r, w|
total += m[1].to_i
count += 1
:continue; # we don't want to terminate the expect call
end
]
result = total / (count * 1.0)
sum = 0
(1..10).each do |i|
sum += i
end
avg = sum/10.0
parley_multiple(15,
[commands1, pattern_action_1],
[commands2, pattern_action_2])
assert(avg == result, "Error avg(#{avg}) != result(#{result}))")
end
=end
def test_nil_timeout
sleep_seconds = 10
read, write, pid = PTY.spawn("/bin/sleep #{sleep_seconds}")
start_time = Time.now
result = read.parley(nil, [:timeout, :timeout], [:eof, :eof])
delta_t = Time.now - start_time
assert(result == :eof, "** ERROR result = #{result}")
assert(delta_t >= sleep_seconds - 1,
"Test ended too quickly: delta_t = #{delta_t}")
end
=begin
# Alternate API, no timeout: parley([pattern, action], ...)
# timeout_seconds defaults to nil which means "no timeout"
def test_missing_timeout
sleep_seconds = 10
read, write, pid = PTY.spawn("/bin/sleep #{sleep_seconds}")
start_time = Time.now
result = read.parley([:timeout, :timeout], [:eof, :eof])
delta_t = Time.now - start_time
assert(result == :eof, "** ERROR result = #{result}")
assert(delta_t >= sleep_seconds - 1,
"Test ended too quickly: delta_t = #{delta_t}")
end
=end
def test_single_match
sin = StringIO.new(@text)
result = sin.parley(0,
[/apple/, "just apple"],
[/white/, "1 too many matches"],
[/dogs/, "2 too many matches"],
[:eof, "very bad"])
assert(result == "just apple", "Invalid result(#{result})")
end
def test_eof_constant
io = File.new("/dev/null", "r")
result = io.parley(20, [:eof, :eof])
assert(result == :eof, "** ERROR result = #{result}")
end
def test_eof_call
io = File.new("/dev/null", "r")
found_eof = false
result = io.parley(20, [:eof, lambda {|m| found_eof = true; nil}])
assert(result.nil?, "** ERROR result = <<#{result}>>")
assert(found_eof == true, "** ERROR found_eof = #{found_eof}")
end
def test_strings
count = 0
io = StringIO.open(@text, "r")
result = io.parley(0,
['red apple', lambda{|m| count += 1; :continue }],
['three dogs', lambda{|m| count += 1; :continue }],
[:eof, lambda{|m| count}] # XXX need to verify unused portion of buffer
)
assert(count == 2, "** ERROR count = #{count}")
assert(result == 2, "** ERROR result = #{result.inspect}")
end
def test_strings_maxread
count = 0
io = StringIO.open(@text, "r")
io.parley_maxread = 10
result = io.parley(0,
['red apple', lambda{|m| count += 1; :continue }],
['three dogs', lambda{|m| count += 1; :continue }],
[:eof, lambda{|m| count}] # XXX need to verify unused portion of buffer
)
assert(count == 2, "** ERROR count = #{count}")
assert(result == 2, "** ERROR result = #{result.inspect}")
end
def test_patterns
colors = ['red\s*?(.*)$', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
count = 0
io = StringIO.open(@text, "r")
result = io.parley(0,
[Regexp.new(colors.join('|')), lambda{|m| count += 1; :continue}],
[:eof, lambda{|m| count}] # XXX need to verify unused portion of buffer
)
assert(count == 2, "** ERROR count = #{count}")
assert(result == 2, "** ERROR result = #{result.inspect}")
end
#
# Test the effect of reading more characters in at a time.
# This means you'll have to be more careful of your patterns so that you
# don't match more than you really want to
#
def test_patterns_maxread
colors = ['red\s*?(.*)$', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
count = 0
io = StringIO.open(@text, "r")
io.parley_maxread = 64 # Note: Up to 64 characters read at a time, so only 1 match
result = io.parley(0,
[Regexp.new(colors.join('|')), lambda{|m| count += 1; :continue}],
[:eof, lambda{|m| count}] # XXX need to verify unused portion of buffer
)
assert(count == 1, "** ERROR count = #{count}")
assert(result == 1, "** ERROR result = #{result.inspect}")
end
#
# Test the effect of reading more characters in at a time.
# This means you'll have to be more careful of your patterns so that you
# don't match more than you really want to
# XXX doesn't work as expected: "\Z matches end of string or just before a \n"
# ? indicates lazy match as opposed to greedy
#
def test_patterns_careful_maxread
re = /
red.*\n | # "red" on a single line
orange.*\n |
yellow.*\n |
green.*\n |
blue.*\n |
indigo.*\n |
violet.*\n
/x
count = 0
io = StringIO.open(@text + @text + @text, "r")
io.parley_maxread = 64 # Note: Up to 64 characters read at a time, so only 1 match
buf_end = nil
io.parley_verbose = true if @test_verbose
result = io.parley(0,
[re, lambda{|m|
count = count + 1;
# puts "COUNT=#{count} MATCH=\"#{m.pre_match}/#{m[0]}/#{m.post_match}\""
:continue}
],
[:eof, lambda{|m|
buf_end = m[0];
count
}
] # XXX need to verify unused portion of buffer
)
assert(count == 3, "** ERROR count = #{count}")
assert(result == 3, "** ERROR result = #{result.inspect}")
# assert(buf_end.length > 0, "** Error buf_end.length=#{buf_end.length}, buf=#{buf_end}")
end
def test_empty_string
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
count = 0
io = StringIO.open("", "r")
result = io.parley(0,
[Regexp.new(colors.join('|')), lambda{|m| count += 1; :continue}],
[:eof, lambda{|m| count}])
assert(count == 0, "** ERROR count = #{count.inspect}")
assert(result == 0, "** ERROR result = #{result.inspect}")
end
def test_ruby_current_version
fnames = []
ftp_to = 20
PTY.spawn("ftp ftp.ruby-lang.org") do |r_f, w_f, pid|
r_f.parley_verbose = true if @test_verbose
hostname = ENV['HOSTNAME']
hostname ||= ""
if !ENV['USER'].nil?
username = ENV['USER']
elsif !ENV['LOGNAME'].nil?
username = ENV['LOGNAME']
else
username = 'guest'
end
# Name (ftp.ruby-lang.org:yourNameHere): ftp
# ftp\n
# Password:
# #{username}\n
# ftp>
# cd pub/ruby\n
r_f.parley(ftp_to,
[/^Name.*:/, lambda {|m| w_f.puts("ftp"); :continue }],
[/ssword:/, lambda {|m| w_f.puts("#{username}@#{hostname}"); :continue }],
[/> /, lambda {|m| w_f.puts("cd pub/ruby"); nil }]
)
# >
# dir\n
r_f.parley(ftp_to, ["> ", lambda {|m| w_f.print "dir\r"}])
# lrwxrwxrwx 1 1014 100 27 Feb 18 12:52 ruby-1.8.7-p334.tar.bz2 -> 1.8/ruby-1.8.7-p334.tar.bz2
r_f.parley(ftp_to,
[/^ftp> /, lambda {|m|
for x in m.pre_match.split("\n")
if x =~ /(ruby.*?\.tar\.gz)/ then
fnames.push $1
end
end
begin
w_f.print "quit\n"
rescue
end
:nil
}],
[:eof, nil])
end
puts "The latest ruby interpreter is #{fnames.sort.pop}"
end
def test_reset_timeout
read, write, pid = PTY.spawn(
# XXX fire off a ruby program, not bash, to get the test behavoir we want
'/bin/bash -x -c "for x in wait done too_late; do sleep 3; echo $x; done"')
read.parley_verbose = true if @test_verbose
result = read.parley(5,
[/wait/, :reset_timeout],
[/done/, :pass ],
[:timeout, :timeout])
assert(result == :pass, "** ERROR result = #{result}")
end
def test_guessing_game
@NGAMES = 2
@UPPER_LIMIT = 100
@UPPER_LIMIT_LOG2 = 8
game = <<-GUESSING_GAME_EOT
BEGIN {puts "0>"; @n = 0}
END { puts "Goodbye!"; }
@secret ||= rand 100
g = $F[0] ? $F[0].strip : ""
z = "?"
if g =~ /\\d+$/m
z = (g.to_i <=> @secret)
case g.to_i <=> @secret
when -1
puts "too low"
when 1
puts "too high"
when 0
puts "correct!"
@secret = rand 100
puts "Ready";
end
else
exit 0 if $F[0] == "exit"
end
@n += 1
puts "\#{@n}>"
GUESSING_GAME_EOT
# DRY: common code for sending a guess
def sendguess resend = false
@myguess = ((@min + @max) / 2).to_i
puts "Resending guess" if resend
puts "Guessing #{@myguess}"
@sin.puts @myguess
@guesses += 1 unless resend
if @guesses > @UPPER_LIMIT_LOG2
"I Lost" # Bug in program if we haven't guessed it already
else
:continue
end
end
def newgame
@min = 0
@max = @UPPER_LIMIT
@guesses = 0
end
def winner
puts "I win!"
@wins += 1
newgame
(@games -= 1) > 0 ? sendguess : "finished" # :continue or "finished"
end
@games = @NGAMES
@wins = 0
# puts "Running: ruby -n -a -e #{game}"
result = nil
pty_return = PTY.spawn('ruby', '-n', '-a', '-e', game) do |sout, sin, pid|
@sin = sin
puts "Sending <CR>"
sin.puts '' # Elicit a prompt from the game
r = select([sout], [], [], 2) # Wait up to 15 seconds for output from guessing game
puts "Wokeup from select with <<#{r.inspect}>>"
newgame
@n_to_reset = 0
sout.parley_maxread = 100
# sout.parley_verbose = true
result = sout.parley(
2,
[/too low/, lambda{|m| @min = @myguess + 1; sendguess}],
[/too high/, lambda{|m| @max = @myguess - 1; sendguess}],
[/correct/, lambda{|m| winner}],
[/>/, lambda{|m| sendguess true}],
[
:timeout,
lambda do |m|
sin.puts ""
@n_to_reset += 1
puts "Resetting timeout #{@n_to_reset}"
if @n_to_reset > 2
sin.puts "exit"
"Timeout"
else
:reset_timeout
end
end
])
end
puts "Script finished, pty_return=#{pty_return}"
assert(result == "finished", "didn't win last game")
# assert(ec == 0, "Bad exit from guessing game")
assert(@wins == @NGAMES, "Didn't win exactly #{@NGAMES} games")
end
end
|
lzrd/parley
|
lib/parley.rb
|
<reponame>lzrd/parley
require 'pty'
# The Parley module is generally used to wrestle with the informal, interactive, text-mode,
# APIs of the world.
#
# Parley is an implementation of an expect-like API. It is designed to
# help port away from Perl Expect based applications.
# Parley was chosen as a name as an alternative to the various "expect" like
# names already in use by other implementations.
#
# The {definition of "parley"}[http://www.thefreedictionary.com/parley] used
# here is: "A discussion or conference, especially one between enemies over
# terms of truce or other matters."
#
# See {the original Expect site at NIST}[http://www.nist.gov/el/msid/expect.cfm] for
# references to the original Expect language based on Tcl.
#
# See the {Perl Expect.pm module}[http://search.cpan.org/~rgiersig/Expect-1.21/Expect.pod].
#
# === Compatibility
# Parley can be used with any class, like PTY, IO or
# StringIO that responds_to?() :eof?, and either :read_nonblock(maxread) or :getc.
#
# If the class also responds to :select, ala IO##select, then Parley will be able to wait
# for additional input to arrive.
#
# === Monkey Patching
# require 'parley' will automatcially add parley() and support methods to the IO class
#
# Author:: <NAME> (mailto:<EMAIL>)
# Copyright:: Copyright (c) 2013 <NAME>
# License:: See LICENSE.txt distributed with this file
#
# == Examples
# === Standard ruby expect vs. equivalent parley usage
# Standard Ruby expect:
# require 'expect'
#
# ...
# input.expect(/pattern/, 10) {|matchdata| code}
#
# Parley:
# require 'parley'
#
# ...
# input.parley(10, [/pattern/, lambda{|matchdata| code}])
#
# === Telnet login using /usr/bin/telnet
# require 'parley'
# input, output, process_id = PTY.spawn("/usr/bin/telnet localhost")
# output.puts '' # hit return to make sure we get some output
# result = input.parley(30, # allow 30 seconds to login
# [ /ogin:/, lambda{|m| output.puts 'username'; :continue} ],
# [ /ssword:/, lambda{|m| output.puts '<PASSWORD>-password'; :continue} ],
# [ /refused/i, "connection refused" ],
# [ :timeout, "timed out" ],
# [ :eof, "command output closed" ],
# [ /\$/, true ] # some string that only appears in the shell prompt
# ])
# if result == true
# puts "Successful login"
# output.puts "date" # This is the important command we had to run
# else
# puts "Login failed because: #{result}"
# end
# # We can keep running commands.
# input.close
# output.close
# id, exit_status = Process.wait2(process_id)
#
module Parley
# Internal: used to set input data that has been received, but not yet matched
#--
# Initialize() is usually not called or doesn't call super(), so
# do implicit instance variable initialization
#++
def unused_buf= (v)
@unused_buf = v
end
# holds the remaining input read from +read_nonblock()+ or +getc()+ but not
# yet used
def unused_buf
@unused_buf = nil unless defined? @unused_buf
@unused_buf
end
# Sets/clears verbose mode to aid debugging.
#
# Debug output is sent to +STDOUT+ unless overridden by +pvout+
def parley_verbose= (truth, pvout = STDOUT)
@pvout = pvout
@parley_verbose = (truth ? true : false)
end
# returns +true+ if debug output is enabled, else +false+
def parley_verbose
@parley_verbose = false unless defined? @parley_verbose
@parley_verbose
end
# sets the maximum number of characters to read from +read_nonblock()+
def parley_maxread= (max_characters = 1)
@parley_maxread = (max_characters > 0) ? max_characters : 1
end
# return the maximum number of characters to read from +read_nonblock()+
def parley_maxread
@parley_maxread = 1 unless defined? @parley_maxread
@parley_maxread
end
# Collect data, from an IO-like object while matching
# match patterns and conditions (i.e. EOF and Timeout) and take corresponding
# actions until an action returns a value not equal to +:continue+ or
# +:reset_timeout+
#
# The parley() method is called with two arguments:
#
# +timeout_seconds+ specifies the amount of time before the +:timeout+
# condition is presented to the pattern/action list.
#
# a variable number of arrays, each array contains a pattern and an action.
#
# * +timeout_seconds+ = nil disables timeout.
# * +timeout_seconds+ <= 0 times out immediately as soon as no data is present
# * +timeout_seconds+ > 0 times out seconds after parley was called unless
# timer is reset by an action returning :reset_timeout
#
# A pattern is either:
# * a RegExp to match input data
# * the symbol :timeout to match the timeout condition from select()
# * the symbol :eof to match the eof?() condition
#
# If an action responds_to?(:call), such as a lambda{|m| code}
# then the action is called with MatchData as an argument.
# In the case of :timeout or :eof, MatchData is from matching:
#
# input_buffer =~ /.*/
#
# A action returning the value +:reset_timeout+ will +:continue+ and reset
# the timeout deadline to a value of +Time.now+ + +timeout_seconds+
#
def parley (timeout_seconds, *actions)
@pvout.puts "parley: timeout_seconds=#{timeout_seconds}" if parley_verbose
case timeout_seconds
when NilClass
deadline = nil
when Numeric
deadline = Time.now + timeout_seconds
else
raise "Invalid timeout parameter: #{timeout_seconds.inspect}"
end
buf = ''
unused_buf ||= ''
# XXX Compatible hack. There are changes coming w.r.t. respond_to? for
# protected methods. Just do a simple poll, and see if it works.
begin
result = IO.select([self], [], [], 0)
has_select = true;
rescue Exception # NoMethodError and ArgumentError are common
has_select = false;
end
begin
# If it is possible to wait for data, then wait for data
t = (deadline ? (deadline - Time.now) : nil)
t = (t.nil? || t >= 0) ? t : 0
# XXX If maxlen > unused_buf.length, then try to get more input?
# Think about above. don't want to use up all of timeout.
if unused_buf.length == 0 && has_select && !IO.select([self], nil, nil, t)
# Timeout condition from IO.select() returns nil
@pvout.print "parley,#{__LINE__}: TIMEOUT buf=\"#{buf}\"\n" if parley_verbose
timeout_handled = nil
result = nil
result = actions.find do|pattern, action|
if pattern == :timeout
timeout_handled = true
if action.respond_to?(:call)
r = action.call(/.*/.match(buf)) # call with entire buffer as a MatchData
else
r = action
end
@pvout.print "parley,#{__LINE__}: TIMEOUT Handled=\"#{r}\"\n" if parley_verbose
break r
else
nil
end
end
@pvout.print "parley,#{__LINE__}: TIMEOUT RESULT=\"#{result}\"\n" if parley_verbose
if (!timeout_handled)
# XXX need to prepend buf to @unusedbuf
unused_buf = buf # save data for next time
raise "timeout"
end
return result unless result == :reset_timeout
matched = true
else
# We've waited, if that was possible, check for data present
if unused_buf.length == 0 && eof?
@pvout.print "parley,#{__LINE__}: EOF Buffer=\"#{buf}\"\n" if parley_verbose
eof_handled = false
result = actions.find do |pattern, action|
case pattern
when :eof
eof_handled = true
if action.respond_to?(:call)
result = action.call(/.*/m.match(buf))
else
result = action
end
break result
else
nil
end
end
unless eof_handled
# XXX need to prepend buf to @unusedbuf
unused_buf = buf # save data for next time
raise "End of file"
end
return result
end
# No timeout and no EOF. There is some input data to look at
# Greedy read:
# buf << self.read_nonblock(maxlen)
if (unused_buf.length > 0)
c = unused_buf.slice!(0..parley_maxread)
elsif (parley_maxread > 1 && self.respond_to?(:read_nonblock))
c = read_nonblock(parley_maxread)
else
c = getc.chr
end
buf << c
# Look for matches to the current buffer content
result = :continue
matched = false
result = actions.each_with_index do |act,i|
# @pvout.print "parley,#{__LINE__}: buf=\"#{buf}\"\tact=#{act[0]}\n" if parley_verbose
m = case act[0]
when Regexp
act[0].match(buf)
when String
act[0] = Regexp.new(act[0]) # caching the regexp conversion
act[0].match(buf)
else
nil
end
if m
@pvout.print "parley,#{__LINE__}: match[#{i}]=\"#{buf}\"\n" if parley_verbose
matched = true
if act[1]
if act[1].respond_to?(:call)
result = act[1].call(m)
else
result = act[1] # no block, just a result
end
else
result = m # no action supplied, return last match
end
buf = '' # consume the buffer (XXX only the part that matched?)
# XXX if the regex had post context, don't consume that.
@pvout.puts "parley,#{__LINE__}: result=#{result}" if parley_verbose
break result
end
result
end
end
if matched == true
@pvout.puts "parley,#{__LINE__}: MATCH, result=#{result}" if parley_verbose
result = case result
when :continue
:continue
when nil # explicit end
break nil
when :reset_timeout
deadline = Time.now + timeout_seconds # XXX vs deadline in lambda closure?
@pvout.puts "parley,#{__LINE__}: deadline=#{deadline.to_s}, continue" if parley_verbose
:continue
else # return with result
break result
end
else
@pvout.puts "parley,#{__LINE__}: no match, implicit :continue, buf=#{buf}" if parley_verbose
result = :continue
end
end while result == :continue
end
end
# Including the Parley module will monkey-patch the IO class
class IO
include Parley
end
|
IreneHodge/ith_palindrome
|
lib/ith_palindrome/version.rb
|
# frozen_string_literal: true
module IthPalindrome
VERSION = "0.1.0"
end
|
mtrautwig/logstash-plugins
|
filters/datesplit.rb
|
<filename>filters/datesplit.rb
# encoding: utf-8
require "logstash/filters/base"
require "logstash/namespace"
# The datesplit filter expands the @timestamp field into its individual
# components, like day of week and hour. This allows for data analysis
# tasks like finding the busiest day, or the time when you best run
# updates.
class LogStash::Filters::DateSplit < LogStash::Filters::Base
config_name "datesplit"
milestone 1
# Specify a time zone canonical ID to be used for date parsing.
# The valid IDs are listed on the [Joda.org available time zones page](http://joda-time.sourceforge.net/timezones.html).
# If this is not specified the platform default will be used.
# Canonical ID is good as it takes care of daylight saving time for you
# For example, `America/Los_Angeles` or `Europe/France` are valid IDs.
config :timezone, :validate => :string
# Specify a locale to be used for date formatting. If this is not specified,
# English will be used
#
# The locale is mostly necessary to be set for formatting month names and
# weekday names.
#
config :locale, :validate => :string, :default => "en"
# field from where the timestamp is taken. If not provided,
# default to using the @timestamp field of the event.
config :source, :validate => :string, :default => "@timestamp"
private
def parseLocale(localeString)
return nil if localeString == nil
matches = localeString.match(/(?<lang>.+?)(?:_(?<country>.+?))?(?:_(?<variant>.+))?/)
lang = matches['lang'] == nil ? "" : matches['lang'].strip()
country = matches['country'] == nil ? "" : matches['country'].strip()
variant = matches['variant'] == nil ? "" : matches['variant'].strip()
return lang.length > 0 ? java.util.Locale.new(lang, country, variant) : nil
end
public
def register
require "java"
@locale = parseLocale(@config["locale"][0]) if @config["locale"] != nil and @config["locale"][0] != nil
end # def register
public
def filter(event)
return unless filter?(event)
if event[@source] && event[@source].is_a?(Time)
time = org.joda.time.DateTime.new(event[@source].to_i * 1000)
if @timezone
time = time.withZone(org.joda.time.DateTimeZone.forID(@timezone))
else
time = time.withZone(org.joda.time.DateTimeZone.getDefault())
end
event["time_year"] = time.year().get()
#event["time_quarter"]
#event["time_week_of_year"]
event["time_month"] = time.monthOfYear().get()
event["time_month_name"] = time.monthOfYear().getAsText(@locale)
event["time_day_of_month"] = time.dayOfMonth().get()
event["time_weekday"] = time.dayOfWeek().get()
event["time_weekday_name"] = time.dayOfWeek().getAsText(@locale)
event["time_hour"] = time.hourOfDay().get()
end
end # def filter
end
|
top1st/peatio-trading-ui-referral
|
lib/peatio_trading_ui/version.rb
|
<gh_stars>1-10
module PeatioTradingUI
VERSION = '1.8.15'
end
|
WalletOne/P2P
|
P2PUI.podspec
|
<reponame>WalletOne/P2P
Pod::Spec.new do |s|
s.name = "P2PUI"
s.version = "0.3.5"
s.summary = "P2PCore - UI Framework for Wallet One P2P"
s.homepage = "https://github.com/WalletOne/P2P.git"
s.license = 'MIT'
s.author = { "Vitaliy" => "<EMAIL>" }
s.ios.deployment_target = '8.0'
s.source = { :git => s.homepage, :tag => s.version.to_s }
s.pod_target_xcconfig = { 'SWIFT_VERSION' => '4.1' }
s.source_files = "P2PUI/**/*.swift"
s.dependency 'P2PCore', '0.3.5'
s.resources = 'P2PUI/**/*.{xib,png,bundle}'
end
|
Elenaltarien/palindrome_checker
|
palindrome_checker.rb
|
# Purpose of program: Test string to see if it's a palindrome. (same when letters are reversed)
# Must pass following tests:
# 1. Get user-input
# 2. Check user-input to see if palindrome.
# 3. If no input entered, inform user.
# 4. If word/phrase not palindrome, inform user.
# 5. If word/phrase is palindrome, inform user.
puts "Welcome to the Palindrome Checker!"
puts "Enter a word or phrase you'd like to test:"
string = gets.chomp
if string == "" || string.strip.empty?
puts "You didn't enter a word or phrase."
else
string.downcase!
string_reverse = string.reverse
if string != string_reverse
puts "Nope, #{string} is not a palindrome."
else
puts "Whoo hoo, #{string} is a palindrome!"
end
end
|
veresiah/TallestTrees
|
lib/trees.rb
|
<filename>lib/trees.rb
class Tree
attr_accessor :scientific_name, :common_name,:family_common_name, :genus, :year, :bibliography, :family, :image_url
@@all = []
def initialize(scientific_name, family_common_name, genus, year, bibliography, family, image_url)
@scientific_name = scientific_name
@family_common_name = family_common_name
@genus = genus
@year = year
@bibliography = bibliography
@family = family
@image_url = image_url
save
end
def self.all
@@all
end
def save
@@all << self
end
# expand? to add queries from tree lists.
#def self.find_all_by_scientifc_name(input)
#Tree.all.select do |tree|
#tree.scientific_name.include? input
#end
#end
end
|
veresiah/TallestTrees
|
lib/api.rb
|
<gh_stars>0
class API
def initialize
@url = "https://trefle.io/api/v1/plants?filter_not%5Bmaximum_height_cm%5D=null&filter%5Bligneous_type%5D=tree&order%5Bmaximum_height_cm%5D=desc&token=#{ENV['API_KEY']}"
end
def get_trees
uri = URI.parse(@url)
resp = Net::HTTP.get(uri)
data = JSON.parse(resp)
tree_data = data["data"]
tree_data.each do |tree_hash|
scientific_name = tree_hash["scientific_name"]
family_common_name = tree_hash["family_common_name"]
genus = tree_hash["genus"]
year = tree_hash["year"]
bibliography = tree_hash["bibliography"]
family = tree_hash["family"]
image_url = tree_hash["image_url"]
Tree.new(scientific_name,family_common_name, genus, year, bibliography, family, image_url)
end
end
end
|
veresiah/TallestTrees
|
lib/cli.rb
|
<gh_stars>0
class CLI
def run
greeting
menu
end
def greeting
system "clear"
puts "Hello there! Welcome to Tallest Trees!".colorize(:green).colorize(:background => :blue)
puts "A CLI displaying details about some of the world's tallest trees.".colorize(:green).colorize( :background => :blue)
sleep (1)
puts "Let's get started!".green
sleep(1)
puts "loading...twenty of the World's Tallest Trees".blink.red
end
def list_trees
API.new.get_trees
Tree.all.each.with_index(1) do |tree, i|
puts "#{i}. #{tree.scientific_name}".light_green
sleep(0.5)
end
end
def menu
list_trees
input = nil
while input != "exit"
puts "Type the number corresponding to the tree that you are interested in or type 'exit' to leave".yellow
input = gets.strip
if input.to_i > 0 && input.to_i < 21
tree = Tree.all[input.to_i-1]
puts "Scientific Name: #{tree.scientific_name}".italic.bold.green
puts "Family Common Name: #{tree.family_common_name}".light_blue
puts "Genus: #{tree.genus}".light_blue
puts "The first year the name of this tree was published: #{tree.year}".light_blue
puts "Publication: #{tree.bibliography}".light_blue
puts "Family: #{tree.family}".light_blue
puts "Click on the link (if provided) to see how this tree looks: #{tree.image_url}".magenta
elsif input == "exit"
goodbye
else
puts "I do not understand. I only accept integers from 1 to 20 or 'exit'".yellow
end
end
end
def goodbye
puts "'Tallest Trees' is being terminated...goodbye".red
sleep(2)
system "clear"
end
end
|
veresiah/TallestTrees
|
config/environment.rb
|
require 'net/http'
require 'open-uri'
require 'json'
require 'dotenv/load'
require 'colorize'
require 'pry'
require_relative "../lib/trees.rb"
require_relative "../lib/api.rb"
require_relative "../lib/cli.rb"
|
siuying/moria
|
app/example_basic_view.rb
|
class ExampleBasicView < UIView
def init
super
view1 = UIView.new
view1.backgroundColor = UIColor.greenColor
self.addSubview view1
view2 = UIView.new
view2.backgroundColor = UIColor.redColor
self.addSubview view2
view3 = UIView.new
view3.backgroundColor = UIColor.blueColor
self.addSubview view3
padding = 10
view1.create_constraint do
top >= superview.top.offset(padding)
left == (superview.left).offset(padding)
bottom == (view3.top).offset(-padding)
right == (view2.left).offset(-padding)
width == view2.width
height == view2.height
height == view3.height
end
view2.create_constraint do
top >= (superview.top).offset(padding)
left == (view1.right).offset(padding)
bottom == (view3.top).offset(-padding)
right == (superview.right).offset(-padding)
width == view1.width
height == view1.height
height == view3.height
end
view3.create_constraint do
top >= (view1.bottom).offset(padding)
left == (superview.left).offset(padding)
bottom == (superview.bottom).offset(-padding)
right == (superview.right).offset(-padding)
height == view1.height
height == view2.height
end
self
end
end
|
siuying/moria
|
spec/view_attribute_spec.rb
|
describe "Moria::ViewAttribute" do
before do
superview = UIView.alloc.init
@view = UIView.alloc.init
superview.addSubview(@view)
@view_attribute = Moria::ViewAttribute.new(@view, NSLayoutAttributeLeft)
end
describe "#offset" do
it "should set constant on view attribute" do
@view_attribute.offset(10).should == @view_attribute
@view_attribute.constant.should == 10
end
end
end
|
siuying/moria
|
lib/moria/base.rb
|
module Moria
LAYOUT_ATTRIBUTES = {
:left => NSLayoutAttributeLeft,
:top => NSLayoutAttributeTop,
:right => NSLayoutAttributeRight,
:bottom => NSLayoutAttributeBottom,
:leading => NSLayoutAttributeLeading,
:trailing => NSLayoutAttributeTrailing,
:width => NSLayoutAttributeWidth,
:height => NSLayoutAttributeHeight,
:centerX => NSLayoutAttributeCenterX,
:centerY => NSLayoutAttributeCenterY,
:baseline => NSLayoutAttributeBaseline
}
end
|
siuying/moria
|
lib/moria/view_constraint.rb
|
<reponame>siuying/moria<filename>lib/moria/view_constraint.rb
module Moria
# A constraint, created by a ConstraintBuilder.
# A view constraint contains two view attribute (view, attribute) and a relation (>=, == or <=).
class ViewConstraint
attr_accessor :first_view_attribute
attr_accessor :second_view_attribute
attr_accessor :layout_priority
attr_accessor :layout_relation
attr_accessor :layout_multiplier
attr_accessor :layout_constant
attr_accessor :installed_view
attr_accessor :layout_constraint
attr_accessor :moria_key
def initialize(view_attribute)
self.first_view_attribute = view_attribute
self.layout_priority = UILayoutPriorityRequired
self.layout_relation = 0.0
self.layout_multiplier = 1.0
self.layout_constant = 0.0
end
# build a NSLayoutConstraint using layout_priority, layout_relation, layout_multiplier, layout_constant, first view attribute and optionally second view attribute
# and then install the constraint on view.
def install
first_view = first_view_attribute.view
first_layout_attribute = first_view_attribute.layout_attribute
second_view = second_view_attribute.view if second_view_attribute
second_layout_attribute = second_view_attribute ? second_view_attribute.layout_attribute : 0
# alignment attributes must have a second_view_attribute
# missing second_view_attribute assumed refer to superview
# left == 10 is same as left == superview.left.offset(10)
if first_view_attribute.alignment_attribute? && second_view.nil?
second_view = first_view.superview
second_layout_attribute = first_layout_attribute
end
self.layout_constant = second_view_attribute.constant if second_view_attribute && second_view_attribute.constant
constraint = LayoutConstraint.constraintWithItem(first_view, attribute:first_layout_attribute, relatedBy:self.layout_relation,
toItem:second_view, attribute: second_layout_attribute, multiplier:self.layout_multiplier, constant: self.layout_constant)
constraint.priority = self.layout_priority
constraint.moria_key = self.moria_key
if second_view
closest_common_superview = first_view.closest_common_superview(second_view)
raise "Cannot install constraint: Could not find a common superview between #{first_view} and #{second_view}" unless closest_common_superview
self.installed_view = closest_common_superview
else
self.installed_view = first_view
end
self.installed_view.addConstraint(constraint)
self.layout_constraint = constraint
self
end
# remove the constraint from view
def uninstall
self.installed_view.removeConstraint(self.layout_constraint)
self.layout_constraint = nil
self.installed_view = nil
end
def offset(constant)
self.layout_constant = constant
self
end
def with
self
end
def priority(value)
self.layout_priority = value
self
end
def priority_high
self.layout_priority = UILayoutPriorityDefaultHigh
self
end
def priority_low
self.layout_priority = UILayoutPriorityDefaultLow
self
end
def key(key)
self.moria_key = key
self
end
def ==(another)
# overrided == for the DSL
if another.is_a?(ViewAttribute)
self.second_view_attribute = another
self.layout_relation = NSLayoutRelationEqual
return self
end
if another.is_a?(Numeric)
self.layout_constant = another
self.layout_relation = NSLayoutRelationEqual
return self
end
if another.is_a?(ViewConstraint)
first_view_attribute == another.first_view_attribute &&
second_view_attribute == another.second_view_attribute &&
layout_relation == another.layout_relation
else
false
end
end
def >=(another)
# overrided == for the DSL
if another.is_a?(ViewAttribute)
self.second_view_attribute = another
self.layout_relation = NSLayoutRelationGreaterThanOrEqual
return self
end
if another.is_a?(Numeric)
self.layout_constant = another
self.layout_relation = NSLayoutRelationGreaterThanOrEqual
return self
end
super
end
def <=(another)
# overrided == for the DSL
if another.is_a?(ViewAttribute)
self.second_view_attribute = another
self.layout_relation = NSLayoutRelationLessThanOrEqual
return self
end
if another.is_a?(Numeric)
self.layout_constant = another
self.layout_relation = NSLayoutRelationLessThanOrEqual
return self
end
super
end
end
end
|
siuying/moria
|
spec/constraint_builder_spec.rb
|
describe "ConstraintBuilder" do
before do
@superview = UIView.alloc.init
@view = UIView.alloc.init
@superview.addSubview(@view)
@builder = Moria::ConstraintBuilder.new(@view)
end
describe "#superview" do
it "should return superview of view" do
@builder.superview.should == @superview
end
end
describe "#install" do
it "should install each of the constraints" do
constraint = mock(:install, :return => true)
@builder.constraints = [constraint]
@builder.install.should == [constraint]
end
end
describe "#top" do
it "should add top constraint to builder" do
@builder.instance_eval do
top == superview.top
end
@builder.constraints.count.should == 1
constraint = @builder.constraints.first
constraint.first_view_attribute.view.should == @view
constraint.first_view_attribute.layout_attribute.should == NSLayoutAttributeTop
constraint.layout_relation.should == NSLayoutRelationEqual
constraint.second_view_attribute.view.should == @view.superview
constraint.second_view_attribute.layout_attribute.should == NSLayoutAttributeTop
end
end
end
|
siuying/moria
|
lib/moria/view_attribute.rb
|
<filename>lib/moria/view_attribute.rb<gh_stars>1-10
module Moria
# represent a attribute in a UIView
class ViewAttribute
attr_accessor :view
attr_accessor :layout_attribute
attr_accessor :constant
def initialize(view, layout_attribute)
@view = view
@layout_attribute = layout_attribute
@constant = nil
end
def size_attribute?
layout_attribute == NSLayoutAttributeWidth || layout_attribute == NSLayoutAttributeHeight
end
def alignment_attribute?
!size_attribute?
end
def offset(constant)
self.constant = constant
self
end
def ==(another)
if another.is_a?(ViewAttribute)
return view == another.view && layout_attribute == another.layout_attribute
end
return false
end
end
end
|
siuying/moria
|
app/example_constant_view.rb
|
class ExampleConstantView < UIView
def init
super
view1 = UIView.new
view1.backgroundColor = UIColor.purpleColor
self.addSubview view1
view2 = UIView.new
view2.backgroundColor = UIColor.orangeColor
self.addSubview view2
view1.create_constraint do
top == 20
left == 20
bottom == -20
right == -20
end
view2.create_constraint do
centerY == 50
centerX == 0
width == 200
height == 100
end
self
end
end
|
siuying/moria
|
app/example_debug_view.rb
|
class ExampleDebugView < UIView
def init
super
view1 = UIView.new
view1.backgroundColor = UIColor.greenColor
addSubview view1
view2 = UIView.new
view2.backgroundColor = UIColor.redColor
addSubview view2
view3 = UILabel.new
view3.backgroundColor = UIColor.blueColor
view3.numberOfLines = 3;
view3.textAlignment = NSTextAlignmentCenter;
view3.font = UIFont.systemFontOfSize(24)
view3.textColor = UIColor.whiteColor
view3.text = "this should look broken! check your console!"
addSubview view3
# install debug extension to NSConstraint, make the debug output more readable
Moria.install_debug_extension
# you can attach debug keys to views
view1.moria_key = "view1"
view2.moria_key = "view2"
view3.moria_key = "view3"
self.moria_key = "superview"
padding = 10
view3.create_constraint do
(height >= 5000).key("ConstantConstraint") # attache keys to constraint
top == superview.top.offset(1)
left == superview.left.offset(1)
bottom == superview.bottom.offset(-1)
right == superview.right.offset(-1)
top == view1.bottom.offset(padding)
left == superview.left.offset(padding)
bottom == superview.bottom.offset(-padding)
right == superview.right.offset(-padding)
height == view1.height
height == view2.height
end
view1.create_constraint do
top == superview.top.offset(padding)
left == superview.left.offset(padding)
bottom == view3.top.offset(-padding)
right == view2.left.offset(-padding)
width == view2.width
height == view3.height
height == view2.height
end
view2.create_constraint do
top == superview.top.offset(padding)
left == view1.right.offset(padding)
bottom == view3.top.offset(-padding)
right == superview.right.offset(-padding)
width == view1.width
height == view1.height
height == view3.height
end
self
end
end
|
siuying/moria
|
spec/view_ext_spec.rb
|
<reponame>siuying/moria<filename>spec/view_ext_spec.rb
describe "View Extension" do
before do
superview = UIView.alloc.init
@view = UIView.alloc.init
superview.addSubview(@view)
end
describe "#create_constraint" do
it "should build constraints on view" do
@view.superview.constraints.size.should == 0
@view.create_constraint do
top == superview.top.offset(10)
left == superview.left
bottom == superview.bottom
right == superview.right
width == 140
(height <= 140).priority_low
end
@view.superview.constraints.size.should == 4
@view.constraints.size.should == 2
end
it "should set view translatesAutoresizingMaskIntoConstraints to false" do
@view.create_constraint do
end
@view.translatesAutoresizingMaskIntoConstraints.should.be.false
end
end
describe "#closest_common_superview" do
it "should return self if input is self" do
superview = UIView.new
superview.closest_common_superview(superview).should == superview
end
it "should find super view of parent/child view" do
superview = UIView.new
subview1 = UIView.new
superview.addSubview subview1
subview1.closest_common_superview(superview).should == superview
superview.closest_common_superview(subview1).should == superview
end
it "should find super view of sibling views" do
superview = UIView.new
subview1 = UIView.new
subview2 = UIView.new
superview.addSubview subview1
superview.addSubview subview2
subview1.closest_common_superview(subview2).should == superview
subview2.closest_common_superview(subview1).should == superview
end
it "should find super view of views in different level" do
superview = UIView.new
subview1 = UIView.new
subview2 = UIView.new
superview.addSubview subview1
superview.addSubview subview2
subview3 = UIView.new
subview4 = UIView.new
subview2.addSubview subview3
subview2.addSubview subview4
subview1.closest_common_superview(subview3).should == superview
subview3.closest_common_superview(subview1).should == superview
subview4.closest_common_superview(subview3).should == subview2
subview3.closest_common_superview(subview4).should == subview2
end
end
Moria::LAYOUT_ATTRIBUTES.each do |name, layout_attribute|
describe "##{name}" do
it "should return attribute" do
view_attribute = @view.send(name)
view_attribute.class.should == Moria::ViewAttribute
view_attribute.view.should == @view
view_attribute.layout_attribute.should == layout_attribute
end
end
end
end
|
siuying/moria
|
lib/moria/constraint_builder.rb
|
<gh_stars>1-10
module Moria
class ConstraintBuilder
attr_reader :view
attr_accessor :constraints
def initialize(view)
@view = view
@constraints = []
end
# install the constraints to view, the return the constraints object
def install
constraints = self.constraints.copy
self.constraints.each do |constraint|
constraint.install
end
self.constraints.clear
constraints
end
# For each of the LAYOUT_ATTRIBUTES, create a method that ViewConstraint
LAYOUT_ATTRIBUTES.each do |name, layout_attribute|
define_method(name) do
constraint_with(layout_attribute)
end
end
def superview
view.superview
end
private
def constraint_with(layout_attribute)
view_attribute = ViewAttribute.new(self.view, layout_attribute)
constraint = ViewConstraint.new(view_attribute)
self.constraints << constraint
constraint
end
end
end
|
siuying/moria
|
spec/layout_constraint_debug_extension_spec.rb
|
<reponame>siuying/moria
describe "Moria::LayoutConstraintDebugExtension" do
before do
@subject = Object.new.extend(Moria::LayoutConstraintDebugExtension)
end
describe "#description_for_object" do
it "should show readable description of view using moria_key" do
view = UIView.new
view.moria_key = "test"
@subject.description_for_object(view).should.include "test"
end
end
describe "#description" do
it "should show priority" do
view1 = UIView.new
view1.moria_key = "view1"
view2 = UIView.new
view2.moria_key = "view2"
constraint = Moria::LayoutConstraint.constraintWithItem(view1, attribute:NSLayoutAttributeTop, relatedBy:NSLayoutRelationEqual,
toItem: view2, attribute: NSLayoutAttributeTop, multiplier: 1, constant: 10)
# enable the extension
constraint.extend(Moria::LayoutConstraintDebugExtension)
desc = constraint.description
desc.should.include "UIView:view1.top == UIView:view2.top + 10.0"
end
end
end
|
siuying/moria
|
lib/moria/layout_constraint_debug_extension.rb
|
<filename>lib/moria/layout_constraint_debug_extension.rb
module Moria
module LayoutConstraintDebugExtension
RELATION_DESCRIPTION = {
NSLayoutRelationEqual => "==",
NSLayoutRelationGreaterThanOrEqual => ">=",
NSLayoutRelationLessThanOrEqual => "<="
}
ATTRIBUTE_DESCRIPTION = {
NSLayoutAttributeTop => "top",
NSLayoutAttributeLeft => "left",
NSLayoutAttributeBottom => "bottom",
NSLayoutAttributeRight => "right",
NSLayoutAttributeLeading => "leading",
NSLayoutAttributeTrailing => "trailing",
NSLayoutAttributeWidth => "width",
NSLayoutAttributeHeight => "height",
NSLayoutAttributeCenterX => "centerX",
NSLayoutAttributeCenterY => "centerY",
NSLayoutAttributeBaseline => "baseline"
}
PRIORITY_DESCRIPTION = {
UILayoutPriorityDefaultHigh => "high",
UILayoutPriorityDefaultLow => "low",
UILayoutPriorityRequired => "required"
}
def description_for_object(obj)
return "#{obj.class}:#{obj.moria_key}" if obj.respond_to?(:moria_key) && obj.moria_key
return "#{obj.class}:0x#{object_id.to_s(16)}"
end
def description
description = ["<"]
description << description_for_object(self)
description << " " + description_for_object(firstItem)
description << "." + ATTRIBUTE_DESCRIPTION[self.firstAttribute] if self.firstAttribute != NSLayoutAttributeNotAnAttribute
description << " " + RELATION_DESCRIPTION[relation]
description << " " + description_for_object(secondItem) if secondItem
description << "." + ATTRIBUTE_DESCRIPTION[secondAttribute] if secondAttribute != NSLayoutAttributeNotAnAttribute
description << " * #{multiplier}" if multiplier != 1
if constant && constant.abs > 0
if secondAttribute == NSLayoutAttributeNotAnAttribute
description << " #{constant}"
else
description << " #{constant < 0 ? '-' : '+'} #{constant.abs}"
end
end
description << " ^" + (PRIORITY_DESCRIPTION[priority] || "@#{priority}") if priority != UILayoutPriorityRequired
description << ">"
description.join('')
end
end
def self.install_debug_extension
NSLayoutConstraint.instance_eval do
include Moria::LayoutConstraintDebugExtension
end
end
end
|
siuying/moria
|
app/example_list_controller.rb
|
class ExampleListController < UITableViewController
ExampleListControllerCellIdentifier = "ExampleListController"
attr_accessor :example_controllers
def init
super
self.title = "Examples"
self.example_controllers = [
ExampleViewController.alloc.initWithTitle("Basic Example", view_class: ExampleBasicView),
ExampleViewController.alloc.initWithTitle("Constant Example", view_class: ExampleConstantView),
ExampleViewController.alloc.initWithTitle("Debugging Example", view_class: ExampleDebugView)
]
self
end
def viewDidLoad
super
self.view.backgroundColor = UIColor.whiteColor
self.tableView.registerClass(UITableViewCell, forCellReuseIdentifier:ExampleListControllerCellIdentifier)
end
# UITableViewDataSource
def tableView(table, cellForRowAtIndexPath: index_path)
view_controller = self.example_controllers[index_path.row]
cell = table.dequeueReusableCellWithIdentifier(ExampleListControllerCellIdentifier, forIndexPath: index_path)
cell.textLabel.text = view_controller.title
return cell
end
def tableView(table, numberOfRowsInSection: section)
self.example_controllers.size
end
# UITableViewDelegate
def tableView(table, didSelectRowAtIndexPath:index_path)
view_controller = self.example_controllers[index_path.row]
self.navigationController.pushViewController(view_controller, animated:true)
end
end
|
siuying/moria
|
spec/view_constraint_spec.rb
|
describe "Moria::ViewConstraint" do
before do
@superview = UIView.new
@view1 = UIView.new
@view2 = UIView.new
@superview.addSubview(@view1)
@superview.addSubview(@view2)
@attribute1 = Moria::ViewAttribute.new(@view1, NSLayoutAttributeHeight)
@attribute2 = Moria::ViewAttribute.new(@view2, NSLayoutAttributeHeight)
@constraint = Moria::ViewConstraint.new(@attribute1)
end
describe "#offset" do
it "should return self with constant set" do
@constraint.offset(10.0)
@constraint.layout_constant.should == 10.0
end
end
describe "#priority" do
it "should return self with priority set" do
@constraint.priority(10.0)
@constraint.layout_priority.should == 10.0
end
end
describe "#priority_high" do
it "should return self with priority set as UILayoutPriorityDefaultHigh" do
@constraint.priority_high
@constraint.layout_priority.should == UILayoutPriorityDefaultHigh
end
end
describe "#priority_low" do
it "should return self with priority set as UILayoutPriorityDefaultLow" do
@constraint.priority_low
@constraint.layout_priority.should == UILayoutPriorityDefaultLow
end
end
describe "#==" do
it "should return constraint with NSLayoutRelationEqual" do
@constraint.==(@attribute2)
@constraint.layout_relation.should == NSLayoutRelationEqual
@constraint.first_view_attribute.should == @attribute1
@constraint.second_view_attribute.should == @attribute2
end
it "should return constraint with == constant relation" do
@constraint == 10
@constraint.layout_relation.should == NSLayoutRelationEqual
@constraint.layout_constant.should == 10
@constraint.first_view_attribute.should == @attribute1
@constraint.second_view_attribute.should == nil
end
end
describe "#>=" do
it "should return constraint with NSLayoutRelationGreaterThan" do
@constraint.>=(@attribute2)
@constraint.layout_relation.should == NSLayoutRelationGreaterThanOrEqual
@constraint.first_view_attribute.should == @attribute1
@constraint.second_view_attribute.should == @attribute2
end
it "should return constraint with >= constant relation" do
@constraint >= 10
@constraint.layout_relation.should == NSLayoutRelationGreaterThanOrEqual
@constraint.layout_constant.should == 10
@constraint.first_view_attribute.should == @attribute1
@constraint.second_view_attribute.should == nil
end
end
describe "#<=" do
it "should return constraint with NSLayoutRelationLessThan" do
@constraint.<=(@attribute2)
@constraint.layout_relation.should == NSLayoutRelationLessThanOrEqual
@constraint.first_view_attribute.should == @attribute1
@constraint.second_view_attribute.should == @attribute2
end
it "should return constraint with <= constant relation" do
@constraint <= 10
@constraint.layout_relation.should == NSLayoutRelationLessThanOrEqual
@constraint.layout_constant.should == 10
@constraint.first_view_attribute.should == @attribute1
@constraint.second_view_attribute.should == nil
end
end
describe "#offset" do
it "should add constraint with offset" do
(@constraint >= @attribute2).with.offset(10)
@constraint.install
@constraint.layout_constant.should == 10
end
end
describe "#install" do
it "should add constraint to superview" do
@constraint >= @attribute2
constraint = @constraint.install
constraint.installed_view.should == @superview
constraint.layout_constraint.should.not.be.nil
constraint.layout_constraint.should.is_a NSLayoutConstraint
end
it "should add constraint on attribute with offset" do
@constraint.==(@attribute2.offset(10))
@constraint.install
@constraint.layout_constant.should == 10
end
it "should add constraint to superview, if it is constant constraint on aligment attribute" do
@attribute1 = Moria::ViewAttribute.new(@view1, NSLayoutAttributeCenterX)
@constraint = Moria::ViewConstraint.new(@attribute1)
@constraint.==(10)
@constraint.install
@constraint.layout_constant.should == 10
@constraint.layout_constraint.firstItem.should == @view1
@constraint.layout_constraint.secondItem.should == @superview
end
end
describe "#uninstall" do
it "should remove constraint" do
@constraint >= @attribute2
@constraint.install
@constraint.uninstall
@superview.constraints.size.should == 0
@constraint.installed_view.should == nil
@constraint.layout_constraint.should == nil
end
end
end
|
siuying/moria
|
lib/moria/layout_constraint.rb
|
<filename>lib/moria/layout_constraint.rb<gh_stars>1-10
module Moria
class LayoutConstraint < NSLayoutConstraint
# a key to asociate with this constraint
attr_accessor :moria_key
end
end
|
siuying/moria
|
app/example_view_controller.rb
|
<gh_stars>1-10
class ExampleViewController < UIViewController
attr_accessor :view_class
def initWithTitle(title, view_class:view_class)
self.init
self.title = title
self.view_class = view_class
self
end
def loadView
self.view = self.view_class.new
self.view.backgroundColor = UIColor.whiteColor
end
def edgesForExtendedLayout
UIRectEdgeNone
end
end
|
siuying/moria
|
lib/moria/view_ext.rb
|
<reponame>siuying/moria
module Moria
module LayoutAttributeExtension
LAYOUT_ATTRIBUTES.each do |key, value|
define_method(key) do
ViewAttribute.new self, value
end
end
end
module LayoutExtension
def create_constraint(&block)
self.translatesAutoresizingMaskIntoConstraints = false
builder = ConstraintBuilder.new(self)
builder.instance_eval(&block)
builder.install
builder
end
# find closest common superview
def closest_common_superview(second_view)
closest_common_superview = nil
second_view_superview = second_view
while (!closest_common_superview && second_view_superview)
first_view_superview = self
while (!closest_common_superview && first_view_superview)
if first_view_superview == second_view_superview
closest_common_superview = second_view_superview
end
first_view_superview = first_view_superview.superview
end
second_view_superview = second_view_superview.superview
end
closest_common_superview
end
end
end
UIView.instance_eval do
include Moria::LayoutAttributeExtension
include Moria::LayoutExtension
attr_accessor :moria_key
end
|
siuying/moria
|
app/app_delegate.rb
|
<filename>app/app_delegate.rb
class AppDelegate
attr_accessor :window
def application(application, didFinishLaunchingWithOptions:launchOptions)
self.window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)
self.window.backgroundColor = UIColor.whiteColor
view_controller = ExampleListController.alloc.init
navController = UINavigationController.alloc.initWithRootViewController(view_controller)
self.window.rootViewController = navController
self.window.makeKeyAndVisible
true
end
end
|
rtomayko/divvy
|
lib/divvy/worker.rb
|
<reponame>rtomayko/divvy<gh_stars>1-10
module Divvy
# Models an individual divvy worker process. These objects are used in both
# the master and the forked off workers to perform common tasks and for basic
# tracking.
class Worker
# The worker number. These are sequential starting from 1 and ending in the
# configured worker concurrency count.
attr_reader :number
# The Unix domain socket file used to communicate with the master process.
attr_reader :socket
# Whether verbose log info should be written to stderr.
attr_accessor :verbose
# Process::Status object result of reaping the worker.
attr_reader :status
# The worker processes's pid. This is $$ when inside the worker process.
attr_accessor :pid
# Create a Worker object. The Master object typically handles this.
def initialize(task, number, socket, verbose = false)
@task = task
@number = number
@socket = socket
@verbose = verbose
@pid = nil
@status = nil
end
# Public: Check whether the worker process is thought to be running. This
# does not attempt to verify the real state of the process with the system.
def running?
@pid && @status.nil?
end
# Public: Send a signal to a running worker process.
#
# signal - String signal name.
#
# Returns true when the process was signaled, false if the process is no
# longer running.
# Raises when the worker process is not thought to be running.
def kill(signal)
fail "worker not running" if @pid.nil?
log "sending signal #{signal}"
Process.kill(signal, @pid)
true
rescue Errno::ESRCH
false
end
# Public: Check whether the current process is this worker process.
#
# Returns true when we're in this worker, false in the master.
def worker_process?
@pid == $$
end
# Public: Fork off a new process for this worker and yield to the block
# immediately in the new child process.
#
# Returns the pid of the new process in the master process. Never returns in
# the child process.
# Raises when the worker process is already thought to be running or has not
# yet been reaped.
def spawn
fail "worker already running" if running?
@status = nil
if (@pid = fork).nil?
@pid = $$
yield
install_signal_traps
main
exit 0
end
@pid
end
# Public: Attempt to reap this worker's process using waitpid. This is a
# no-op if the process is not thought to be running or is marked as already
# being reaped. This should only be called in the master process.
#
# Returns the Process::Status object if the process was reaped, nil if the
# process was not reaped because it's still running or is already reaped.
def reap
if @status.nil? && @pid && Process::waitpid(@pid, Process::WNOHANG)
@status = $?
log "exited, reaped pid #{@pid} (status: #{@status.exitstatus})"
@status
end
end
# Internal: The main worker loop. This is called after a new worker process
# has been setup with signal traps and whatnot and connects to the master in
# a loop to retrieve task items. The worker process exits if this method
# returns or raises an exception.
def main
fail "Worker#main called in master process" if !worker_process?
log "booted with pid #{@pid}"
@task.after_fork(self)
while arguments = dequeue
@task.process(*arguments)
break if @shutdown
end
# worker should exit on return
rescue Exception => boom
message = "error: worker [#{number}]: #{boom.class} #{boom.to_s}"
if verbose || ENV['DIVVY_VERBOSE_TRACE']
backtrace = boom.backtrace.join("\n").gsub(/^/, " ").gsub("#{Dir.pwd}/", "")
message << "\n#{backtrace}"
end
$stderr.puts message
exit 1
end
# Internal: Retrieve an individual task item from the master process. Opens
# a new socket, reads and unmarshals a single task item.
#
# Returns an Array containing the arguments yielded by the dispatcher.
def dequeue
client = UNIXSocket.new(@socket)
r, w, e = IO.select([client], nil, [client], nil)
return if !e.empty?
if data = client.read(16384)
Marshal.load(data)
end
rescue Errno::ECONNRESET => boom
# server went away between getting in the backlog and reading actual data
# we treat this as if no data was read
rescue Errno::ENOENT => boom
# socket file went away, bail out
ensure
client.close if client
end
def install_signal_traps
fail "attempt to install worker signal handling in master" if !worker_process?
%w[INT TERM QUIT].each do |signal|
trap signal do
next if @shutdown
@shutdown = true
log "#{signal} received. initiating graceful shutdown..."
end
end
end
def log(message)
return if !verbose
$stderr.printf("worker [%d]: %s\n", number, message)
end
end
end
|
mauriciofloresl/aztecnews
|
app/models/user.rb
|
class User < ActiveRecord::Base
has_secure_password
validates_uniqueness_of :email
enum role: [:user, :admin]
end
|
mauriciofloresl/aztecnews
|
app/controllers/admin/articles_controller.rb
|
<reponame>mauriciofloresl/aztecnews<gh_stars>0
class Admin::ArticlesController < Admin::ApplicationController
before_action :set_article, only: [:show, :edit, :update, :destroy, :approve, :reject]
def index
@articles = Article.where(status: 0)
end
def approved
@articles = Article.where(status: 1)
end
def approve
authorize @article
respond_to do |format|
if @article.update(status: :approved)
flash.now[:notice] = 'Article was successfully approved.'
format.js
else
format.html { render :edit }
format.json { render json: @article.errors, status: :unprocessable_entity }
end
end
end
def reject
authorize @article
respond_to do |format|
if @article.update(status: :rejected)
flash.now[:alert] = 'Article was successfully rejected.'
format.js
else
format.html { render :edit }
format.json { render json: @article.errors, status: :unprocessable_entity }
end
end
end
def show
end
def new
@article = Article.new
end
def edit
end
def create
@article = Article.new(article_params)
authorize @article
if @article.save
redirect_to [:admin, @article], notice: 'Article was successfully created.'
else
render :new
end
end
def update
authorize @article
if @article.update(article_params)
redirect_to [:admin, @article], notice: 'Article was successfully updated.'
else
render :edit
end
end
def destroy
authorize @article
@article.destroy
redirect_to articles_url, notice: 'Article was successfully destroyed.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_article
@article = Article.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def article_params
params.require(:article).permit(:link, :approved, :category_id)
end
end
|
mauriciofloresl/aztecnews
|
db/schema.rb
|
<filename>db/schema.rb
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20160510175527) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "articles", force: :cascade do |t|
t.string "link"
t.integer "status", default: 0
t.integer "category_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "title"
t.text "description"
t.integer "length"
t.string "image"
t.integer "issue_id"
end
add_index "articles", ["category_id"], name: "index_articles_on_category_id", using: :btree
add_index "articles", ["issue_id"], name: "index_articles_on_issue_id", using: :btree
create_table "categories", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "issues", force: :cascade do |t|
t.date "issued_at"
t.integer "guid"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "email"
t.string "password_digest"
t.integer "role", default: 0
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
add_foreign_key "articles", "categories"
add_foreign_key "articles", "issues"
end
|
mauriciofloresl/aztecnews
|
config/routes.rb
|
Rails.application.routes.draw do
namespace :admin do
get 'log_in' => 'sessions#new', as: :log_in
get 'log_out' => 'sessions#destroy', as: :log_out
root 'articles#new'
get 'articles/approved' => 'articles#approved', as: 'approved_articles'
post 'articles/approve/:id' => 'articles#approve', as: 'approve_article'
post 'articles/reject/:id' => 'articles#reject', as: 'reject_article'
get 'articles/unauthorized' => 'articles#unauthorized', as: 'unauthorized'
post 'sessions/' => 'sessions#create'
resources :articles
resources :categories
end
get 'issues/latest' => 'issues#latest', as: 'issue_latest'
resources :issues, only: [:index, :show]
root 'pages#home'
end
|
mauriciofloresl/aztecnews
|
app/controllers/pages_controller.rb
|
<reponame>mauriciofloresl/aztecnews
class PagesController < ApplicationController
def home
@issues = Issue.all
end
end
|
wanelo/runner
|
lib/runner.rb
|
require 'runner/version'
require 'runner/runner'
module Runner
end
|
wanelo/runner
|
lib/runner/environment.rb
|
module Runner
class Environment
def load!
set_environment
load_rails
configure_logger
end
def set_environment
ENV['RAILS_ENV'] ||= 'development'
ENV['RACK_ENV'] ||= ENV['RAILS_ENV']
end
def load_rails
begin
require 'rails'
if ::Rails.application.respond_to?(:eager_load)
require File.expand_path('config/environment.rb')
::Rails.application.eager_load!
else
require File.expand_path('config/application.rb')
::Rails::Application.initializer 'runner.load_rails' do
::Rails.application.config.eager_load = true
end
require File.expand_path('config/environment.rb')
end
rescue LoadError
end
end
def configure_logger
if defined?(Rails) && ENV['LOGFILE']
Rails.logger = Logger.new(ENV['LOGFILE'])
end
end
end
end
|
wanelo/runner
|
lib/runner/runner.rb
|
require 'runner/environment'
module Runner
class Runner
attr_reader :args
def initialize(args)
@args = args
end
def run
handle_signals!
Environment.new.load!
eval(args.join(' '))
end
def handle_signals!
Signal.trap('INT') { exit }
Signal.trap('TERM') { exit }
end
end
end
|
json-next/json-next
|
lib/json/next/pattern.rb
|
# encoding: utf-8
module JSON
module Next
## note: regex pattern \\ needs to get escaped twice, thus, \\.
## and for literal \\ use \\\\\.
## todo: check for newlines [^] incl. newline ?
## note: add named captures for "inner" unquotes string values
###############
##### quotes
BACKTICK_ML_QUOTE = %< ` (?<backtick_ml_quote>
(?:
\\\\. | [^`]
)*
)
`
>
## => \\\\. -- allow backslash escapes e.g. \n \t \\ etc.
## => [^`] -- everything except backquote
## todo/fix - check if [^`] includes/matches newline too (yes)? -- add \n for multi-line!
SINGLE_QUOTE = %< ' (?<single_quote>
(?:
\\\\. | [^']
)*
)
'
>
DOUBLE_QUOTE = %< " (?<double_quote>
(?:
\\\\. | [^"]
)*
)
"
>
#######################
#### comments
CLANG_ML_COMMENT = %< /\\*
.*?
\\*/
>
## use . instead of [^] - why? why not?
## note: check if . incl. newlines too (only in multi-line (m) option - why? why not??
## fix/todo: include newline!!! \n - for multi-line!!!
## note: *? is NON-greedy
CLANG_COMMENT = %< //
.*?
(?:
\\n | $
)
>
## note: check if . incl. newlines too (only in multi-line (m) option - why? why not??
## note: *? is NON-greedy
SHELL_COMMENT = %< [#]
.*?
(?:
\\n | $
)
>
## note: use [#] instead of # to avoid confusion with # comment in regex
KEYWORDS = %<
(?:
true | false | null
)
(?=
[^\\w_$] | $
)
>
IDENTIFIER = %<
(?<identifier>
[a-zA-Z_$]
[\\w_$]*
)
>
## note: allow extra chars for identifier (extended)
## e.g. allow dash (-) e.g:
## babel-preset-es2015
## core-js
## cross-spawn
## eslint-config-jquery
## and others
IDENTIFIER_EXTENDED = %<
(?<identifier>
[a-zA-Z_$]
[\\w_$\\-]*
)
>
TRAILING_COMMA = %<
(?<trailing_comma>,)
(?=
\\s*
[}\\]]
)
>
UNESCAPE_MAP = {
%<\\"> => %<">, ## "\\\"" => "\"",
%<\\`> => %<`>, ## "\\`" => "`",
%<\\'> => %<'> ## "\\'" => "'"
}
ML_ESCAPE_MAP = {
%<\n> => %<\\n>, ## "\n" => "\\n",
%<\r> => %<\\r>, ## "\r" => "\\r",
%<\t> => %<\\t>, ## "\t" => "\\t",
%<"> => %<\\"> ## "\"" => "\\\""
}
end # module Next
end # module JSON
|
json-next/json-next
|
test/test_parser_hanson.rb
|
# encoding: utf-8
###
# to run use
# ruby -I ./lib -I ./test test/test_parser_hanson.rb
require 'helper'
class TestParser < MiniTest::Test
def test_hanson
sample1, exp1 = TestBlockFile.read_utf8( 'hanson1' )
puts HANSON.convert( sample1 )
pp HANSON.parse( sample1 )
assert_equal eval( exp1 ), HANSON.parse( sample1 )
end
end
|
json-next/json-next
|
lib/json/next.rb
|
<filename>lib/json/next.rb
# encoding: utf-8
require 'json'
require 'strscan' ## StringScanner
require 'pp'
# our own code
require 'json/next/version' # note: let version always go first
require 'json/next/pattern' # shared utils for "custom" parser
require 'json/next/commata'
require 'json/next/parser/hanson'
require 'json/next/parser/son'
require 'json/next/parser/jsonx'
# say hello
puts JSON::Next.banner if defined?( $RUBYLIBS_DEBUG )
|
json-next/json-next
|
test/test_parser_son.rb
|
<filename>test/test_parser_son.rb
# encoding: utf-8
###
# to run use
# ruby -I ./lib -I ./test test/test_parser_son.rb
require 'helper'
class TestParserSon < MiniTest::Test
def test_son
sample1, exp1 = TestBlockFile.read_utf8( 'son1' )
puts SON.convert( sample1 )
assert_equal eval(exp1), SON.parse( sample1 )
end
end
|
json-next/json-next
|
test/test_parser_jsonx.rb
|
<filename>test/test_parser_jsonx.rb<gh_stars>10-100
# encoding: utf-8
###
# to run use
# ruby -I ./lib -I ./test test/test_parser_jsonx.rb
require 'helper'
class TestParserJsonx < MiniTest::Test
def test_jsonx
sample1, exp1 = TestBlockFile.read_utf8( 'jsonx1' )
puts JSONX.convert( sample1 )
assert_equal eval(exp1), JSONX.parse( sample1 )
sample2, exp2 = TestBlockFile.read_utf8( 'jsonx2' )
puts JSONX.convert( sample2 )
assert_equal eval(exp2), JSONX.parse( sample2 )
end
end
|
json-next/json-next
|
lib/json/next/commata.rb
|
# encoding: utf-8
module JSON
module Next
### auto-add commas for objects and arrays
class Commata
## convenience helper
def self.convert( str, opts={} )
self.new.convert( str, opts )
end
def convert( str, opts={} )
@debug = opts.fetch( :debug, false )
@out = ""
@buffer = StringScanner.new( str )
skip_whitespaces
parse_value
@out
end
def debug?() @debug; end
def skip_whitespaces
@buffer.skip( /[ \t\n]*/ ) ## skip trailing WHITESPACE
end
def parse_string
if @buffer.peek(1) == '"' ## double quote
@buffer.getch # consume double quote
value = @buffer.scan( /(\\.|[^"])*/ )
@buffer.getch # consume double quote
puts %{string value >>#{value}<<} if debug?
@out << ' "'
@out << value
@out << '" '
skip_whitespaces
else
puts "!! format error: string literal - expected opening quote (\") - rest is >>#{@buffer.rest}<<"
end
end
def parse_object
if @buffer.peek(1) == '{'
@buffer.getch # consume '{'
@out << ' { '
skip_whitespaces
if @buffer.peek(1) == '}' ## empty object?
@buffer.getch # consume '{'
@out << ' } '
skip_whitespaces
return
end
loop do
parse_string
if @buffer.peek(1) == ':'
@buffer.getch # consume ':'
@out << ' : '
skip_whitespaces
parse_value
if @buffer.peek(1) == '}'
@buffer.getch # consume '}'
@out << ' } '
skip_whitespaces
return ## use break - why? why not?
else
if @buffer.peek(1) == ','
@buffer.getch # consume ','
@out << ' , '
skip_whitespaces
else
puts "object literal - auto-add comma for key-value pair" if debug?
@out << ' , '
end
end
else
puts "!! format error: object literal - expected colon (:) - rest is >>#{@buffer.rest}<<"
end
end
else
puts "!! format error: object literal - expected curly open bracket ({) - rest is >>#{@buffer.rest}<<"
end
end # method parse_object
def parse_array
if @buffer.peek(1) == '['
@buffer.getch # consume '['
@out << ' [ '
skip_whitespaces
if @buffer.peek(1) == ']' ## empty array?
@buffer.getch # consume ']'
@out << ' ] '
skip_whitespaces
return
end
loop do
parse_value
if @buffer.peek(1) == ']'
@buffer.getch # consume ']'
@out << ' ] '
skip_whitespaces
return ## use break - why? why not?
else
if @buffer.peek(1) == ','
@buffer.getch # consume ','
@out << ' , '
skip_whitespaces
else
puts "array literal - auto-add comma for value" if debug?
@out << ' , '
end
end
end
else
puts "!! format error: array literal - expected square open bracket ([) - rest is >>#{@buffer.rest}<<"
end
end # method parse_array
def parse_value
if @buffer.peek(1) == '{'
parse_object
elsif @buffer.peek(1) == '['
parse_array
elsif @buffer.peek(1) == '"'
parse_string
else
## assume number or literal/identifier
value = @buffer.scan( /[_$a-zA-Z0-9.+\-]+/ )
puts %{literal value >>#{value}<<} if debug?
@out << " "
@out << value
@out << " "
skip_whitespaces
end
## todo/fix: check if eof reached ?? if not report warning - more data available??
## wrap in object ({}) or array ([])
end
end # class Commata
end # module Next
end # module JSON
|
json-next/json-next
|
lib/json/next/parser/son.rb
|
# encoding: utf-8
###
# based on github.com/aleksandergurin/simple-object-notation
# Thanks to <NAME>
module SON
DOUBLE_QUOTE = JSON::Next::DOUBLE_QUOTE
SHELL_COMMENT = JSON::Next::SHELL_COMMENT
def self.strip_comments( text ) ## pass 1
text.gsub( /#{DOUBLE_QUOTE}|#{SHELL_COMMENT}/ox ) do |match|
## puts "match: >>#{match}<< : #{match.class.name}"
if match[0] == ?# ## comments start with #
## puts "!!! removing comments"
'' ## remove / strip comments
else
match
end
end
end
def self.convert( text )
# text is the SON string to convert.
text = strip_comments( text ) ## pass 1
text = JSON::Next::Commata.convert( text ) ## pass 2 - auto-add (missing optional) commas
text
end
def self.parse( text )
JSON.parse( self.convert( text ) )
end
end # module SON
|
json-next/json-next
|
test/test_version.rb
|
<filename>test/test_version.rb
# encoding: utf-8
###
# to run use
# ruby -I ./lib -I ./test test/test_version.rb
require 'helper'
class TestVersion < MiniTest::Test
def test_version
pp JSON::Next::UNESCAPE_MAP
pp JSON::Next::ML_ESCAPE_MAP
pp JSON::Next::BACKTICK_ML_QUOTE
puts JSON::Next::BACKTICK_ML_QUOTE
pp JSON::Next::SINGLE_QUOTE
puts JSON::Next::SINGLE_QUOTE
pp JSON::Next::DOUBLE_QUOTE
puts JSON::Next::DOUBLE_QUOTE
pp JSON::Next::CLANG_ML_COMMENT
puts JSON::Next::CLANG_ML_COMMENT
pp JSON::Next::CLANG_COMMENT
puts JSON::Next::CLANG_COMMENT
puts JSON::Next::VERSION
assert true
## assume everything ok if get here
end
end # class TestVersion
|
json-next/json-next
|
test/helper.rb
|
<filename>test/helper.rb<gh_stars>10-100
# encoding: utf-8
## minitest setup
require 'minitest/autorun'
$RUBYLIBS_DEBUG = true
## our own code
require 'json/next'
class TestBlockFile
def self.read_utf8( path )
BlockFile.read_utf8( "#{JSON::Next.root}/test/data/#{path}.txt" )
end
end
class BlockFile
def self.read_utf8( path )
text = File.open( path, 'r:bom|utf-8' ).read
reader = BlockReader.new( text )
reader.blocks
end
end
class BlockReader
attr_reader :blocks
def initialize( text )
## split blocks by ---
@blocks = text.split( /^\s*---\s*$/ )
end
end ## block reader
|
json-next/json-next
|
lib/json/next/version.rb
|
# encoding: utf-8
module JSON
module Next
MAJOR = 1 ## todo: namespace inside version or something - why? why not??
MINOR = 2
PATCH = 1
VERSION = [MAJOR,MINOR,PATCH].join('.')
def self.version
VERSION
end
def self.banner
"json-next/#{VERSION} on Ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE}) [#{RUBY_PLATFORM}]"
end
def self.root
"#{File.expand_path( File.dirname(File.dirname(File.dirname(File.dirname(__FILE__)))) )}"
end
end # module Next
end # module JSON
|
json-next/json-next
|
lib/json/next/parser/jsonx.rb
|
# encoding: utf-8
##
## JSON with Extensions (JSONX) or
## JSON 1.1 - JSON XI
module JSONX
BACKTICK_ML_QUOTE = JSON::Next::BACKTICK_ML_QUOTE
SINGLE_QUOTE = JSON::Next::SINGLE_QUOTE
DOUBLE_QUOTE = JSON::Next::DOUBLE_QUOTE
CLANG_ML_COMMENT = JSON::Next::CLANG_ML_COMMENT
CLANG_COMMENT = JSON::Next::CLANG_COMMENT
SHELL_COMMENT = JSON::Next::SHELL_COMMENT
KEYWORDS = JSON::Next::KEYWORDS
IDENTIFIER = JSON::Next::IDENTIFIER_EXTENDED
TRAILING_COMMA = JSON::Next::TRAILING_COMMA
UNESCAPE_MAP = JSON::Next::UNESCAPE_MAP
ML_ESCAPE_MAP = JSON::Next::ML_ESCAPE_MAP
def self.strip_comments( text ) ## pass 1
text.gsub( /#{BACKTICK_ML_QUOTE}|#{SINGLE_QUOTE}|#{DOUBLE_QUOTE}|#{SHELL_COMMENT}|#{CLANG_ML_COMMENT}|#{CLANG_COMMENT}/ox ) do |match|
## puts "match: >>#{match}<< : #{match.class.name}"
if match[0] == ?/ || match[0] == ?# ## comments start with // or /* or #
## puts "!!! removing comments"
'' ## remove / strip comments
else
match
end
end
end
### note: same as hanson (see parser/hanson.rb)
def self.normalize_quotes( text ) ## pass 2
text.gsub( /#{BACKTICK_ML_QUOTE}|#{SINGLE_QUOTE}|#{DOUBLE_QUOTE}/ox ) do |match|
## puts "match: >>#{match}<< : #{match.class.name}"
m = Regexp.last_match
if m[:backtick_ml_quote]
## puts "!!! ml_quote -- convert to double quotes"
str = m[:backtick_ml_quote]
str = str.gsub( /\\./ ) {|r| UNESCAPE_MAP[r] || r }
str = str.gsub( /[\n\r\t"]/ ) { |r| ML_ESCAPE_MAP[r] }
'"' + str + '"'
elsif m[:single_quote]
## puts "!!! single_quote -- convert to double quotes"
str = m[:single_quote]
str = str.gsub( /\\./ ) {|r| UNESCAPE_MAP[r] || r }
str = str.gsub( /"/, %{\\"} )
'"' + str + '"'
else
match
end
end
end
def self.convert( text )
## pass 1: remove/strip comments
text = strip_comments( text )
## pass 2: requote/normalize quotes
text = normalize_quotes( text )
## pass 3: quote unquoted and remove trailing commas
text = text.gsub( /#{KEYWORDS}|#{IDENTIFIER}|#{DOUBLE_QUOTE}|#{TRAILING_COMMA}/ox ) do |match|
## puts "match: >>#{match}<< : #{match.class.name}"
m = Regexp.last_match
if m[:identifier]
## puts "!!! identfier -- wrap in double quotes"
'"' + m[:identifier] + '"'
elsif m[:trailing_comma]
## puts "!!! trailing comma -- remove"
''
else
match
end
end
## pass 4 - auto-add (missing optional) commas
text = JSON::Next::Commata.convert( text )
text
end
def self.parse( text )
JSON.parse( self.convert( text ) )
end
end # module JSONX
## add some aliases
JSONXI = JSONX
JSONII = JSONX
JSON11 = JSONX
|
json-next/json-next
|
test/test_commata.rb
|
<gh_stars>10-100
# encoding: utf-8
###
# to run use
# ruby -I ./lib -I ./test test/test_commata.rb
require 'helper'
class TestCommata < MiniTest::Test
def test_commata
sample1, exp1 = TestBlockFile.read_utf8( 'commata1' )
sample2a, exp2a = TestBlockFile.read_utf8( 'commata2a' )
sample2b, exp2b = TestBlockFile.read_utf8( 'commata2b' )
json1 = JSON::Next::Commata.convert( sample1, debug: true )
puts json1
assert_equal eval(exp1), JSON.parse( json1 )
json2a = JSON::Next::Commata.convert( sample2a, debug: true )
puts json2a
assert_equal eval(exp2a), JSON.parse( json2a )
json2b = JSON::Next::Commata.convert( sample2b, debug: true )
puts json2b
assert_equal eval(exp2b), JSON.parse( json2b )
end
end
|
json-next/json-next
|
lib/json/next/parser/hanson.rb
|
# encoding: utf-8
###
# based on github.com/timjansen/hanson
# Thanks to <NAME>
module HANSON
BACKTICK_ML_QUOTE = JSON::Next::BACKTICK_ML_QUOTE
SINGLE_QUOTE = JSON::Next::SINGLE_QUOTE
DOUBLE_QUOTE = JSON::Next::DOUBLE_QUOTE
CLANG_ML_COMMENT = JSON::Next::CLANG_ML_COMMENT
CLANG_COMMENT = JSON::Next::CLANG_COMMENT
KEYWORDS = JSON::Next::KEYWORDS
IDENTIFIER = JSON::Next::IDENTIFIER
TRAILING_COMMA = JSON::Next::TRAILING_COMMA
UNESCAPE_MAP = JSON::Next::UNESCAPE_MAP
ML_ESCAPE_MAP = JSON::Next::ML_ESCAPE_MAP
def self.strip_comments( text ) ## pass 1
text.gsub( /#{BACKTICK_ML_QUOTE}|#{SINGLE_QUOTE}|#{DOUBLE_QUOTE}|#{CLANG_ML_COMMENT}|#{CLANG_COMMENT}/ox ) do |match|
## puts "match: >>#{match}<< : #{match.class.name}"
if match[0] == ?/ ## comments start with // or /*
## puts "!!! removing comments"
'' ## remove / strip comments
else
match
end
end
end
def self.normalize_quotes( text ) ## pass 2
text.gsub( /#{BACKTICK_ML_QUOTE}|#{SINGLE_QUOTE}|#{DOUBLE_QUOTE}/ox ) do |match|
## puts "match: >>#{match}<< : #{match.class.name}"
m = Regexp.last_match
if m[:backtick_ml_quote]
## puts "!!! ml_quote -- convert to double quotes"
str = m[:backtick_ml_quote]
str = str.gsub( /\\./ ) {|r| UNESCAPE_MAP[r] || r }
str = str.gsub( /[\n\r\t"]/ ) { |r| ML_ESCAPE_MAP[r] }
'"' + str + '"'
elsif m[:single_quote]
## puts "!!! single_quote -- convert to double quotes"
str = m[:single_quote]
str = str.gsub( /\\./ ) {|r| UNESCAPE_MAP[r] || r }
str = str.gsub( /"/, %{\\"} )
'"' + str + '"'
else
match
end
end
end
def self.convert( text )
# text is the HanSON string to convert.
# todo: add keep_line_numbers options - why? why not?
# see github.com/timjansen/hanson
## pass 1: remove/strip comments
text = strip_comments( text )
## pass 2: requote/normalize quotes
text = normalize_quotes( text )
## pass 3: quote unquoted and remove trailing commas
text = text.gsub( /#{KEYWORDS}|#{IDENTIFIER}|#{DOUBLE_QUOTE}|#{TRAILING_COMMA}/ox ) do |match|
## puts "match: >>#{match}<< : #{match.class.name}"
m = Regexp.last_match
if m[:identifier]
## puts "!!! identfier -- wrap in double quotes"
'"' + m[:identifier] + '"'
elsif m[:trailing_comma]
## puts "!!! trailing comma -- remove"
''
else
match
end
end
text
end
def self.parse( text )
JSON.parse( self.convert( text ) )
end
end # module HANSON
|
javagg/GitlabLicGen
|
keygen.rb
|
<reponame>javagg/GitlabLicGen
require 'openssl'
require 'gitlab/license'
license_text=<<HERE
-----<KEY>
HERE
private_key = OpenSSL::PKey::RSA.new license_text
puts "Private Key:"
puts private_key
public_key = private_key.public_key
puts "Public Key:"
puts public_key
Gitlab::License.encryption_key = private_key
license = Gitlab::License.new
license.licensee = {
"Name" => "agm",
"Company" => "AnGaoMeng Ltd.",
"Email" => "<EMAIL>"
}
today = Date.today
license.starts_at = today
license.expires_at = today.next_day(365)
license.notify_admins_at = today.next_day(350)
license.notify_users_at = today.next_day(360)
license.block_changes_at = today.next_day(370)
license.restrictions = {
active_user_count: 1000
}
data = license.export
puts "License:"
puts data
|
geomaster58/KeeneysAwesomeViewTool
|
lib/KeeneysAwesomeViewTool.rb
|
<reponame>geomaster58/KeeneysAwesomeViewTool
require "KeeneysAwesomeViewTool/version"
require "KeeneysAwesomeViewTool/renderer"
|
adrian-gomez/ward-web
|
spec/views/instances/show.html_spec.rb
|
require 'rails_helper'
RSpec.describe 'instances/show' do
let(:instance) { create(:instance) }
before { assign(:instance, instance) }
it 'renders attributes in <p>' do
render
end
end
|
adrian-gomez/ward-web
|
spec/views/instances/index.html_spec.rb
|
require 'rails_helper'
RSpec.describe 'instances/index' do
let(:instances) { [create(:instance), create(:instance)] }
before(:each) { assign(:instances, instances) }
it 'renders a list of instances' do
render
end
end
|
adrian-gomez/ward-web
|
spec/routing/instances_routing_spec.rb
|
require 'rails_helper'
RSpec.describe InstancesController do
describe 'routing' do
it 'routes to #index' do
expect(:get => '/instances').to route_to('instances#index')
end
it 'routes to #show' do
expect(get: '/instances/1').to route_to('instances#show', id: '1')
end
it 'routes to #edit' do
expect(get: '/instances/1/edit').to route_to('instances#edit', id: '1')
end
it 'routes to #update via PUT' do
expect(put: '/instances/1').to route_to('instances#update', id: '1')
end
it 'routes to #update via PATCH' do
expect(patch: '/instances/1').to route_to('instances#update', id: '1')
end
it 'routes to #destroy' do
expect(delete: '/instances/1').to route_to('instances#destroy', id: '1')
end
end
end
|
adrian-gomez/ward-web
|
spec/factories/instances.rb
|
FactoryGirl.define do
factory :instance do
sequence(:ip) { |n| "127.0.0.#{n}" }
label 'Example Instance'
end
end
|
adrian-gomez/ward-web
|
app/models/reading.rb
|
class Reading
include Mongoid::Document
include Mongoid::Timestamps
belongs_to :instance
embeds_one :data, class_name: 'ReadingData'
validates! :instance, presence: true
validates :data, presence: true
def self.from_last_hours(hours = 12)
self.where(:created_at.gte => (Time.now - hours.hours))
end
def as_json(*args)
data = super
data['created_at'] = self.created_at.utc.iso8601
data['updated_at'] = self.updated_at.utc.iso8601
data
end
end
|
adrian-gomez/ward-web
|
app/models/instance.rb
|
<reponame>adrian-gomez/ward-web
class Instance
include Mongoid::Document
include Mongoid::Timestamps
field :label, type: String
field :ip, type: String
has_many :readings
validates :ip, presence: true
validates :ip, uniqueness: true, allow_nil: true
validate :valid_ip
private
def valid_ip
IPAddress.parse(self.ip)
rescue ArgumentError
self.errors.add(:ip, 'is invalid')
end
end
|
adrian-gomez/ward-web
|
spec/factories/instance_data.rb
|
FactoryGirl.define do
factory :reading_data do
disk_usage { rand * 100 }
cpu_usage { rand * 100 }
process_list { %W[process-#{rand(1..100)}]*10 }
reading
# after_build
end
end
|
adrian-gomez/ward-web
|
spec/controllers/api/readings_controller_spec.rb
|
require 'rails_helper'
RSpec.describe Api::ReadingsController do
let!(:instance) { create(:instance) }
describe 'POST #create' do
before { request.env['REMOTE_ADDR'] = instance.ip }
context 'with valid params' do
let(:valid_attributes) { attributes_for(:reading) }
it 'creates a new instance reading' do
expect {
post :create, { reading: valid_attributes }
}.to change(instance.readings, :count).by(1)
end
it 'returns a success response' do
post :create, { reading: valid_attributes }
expect(response).to be_success
end
it 'returns a success message' do
post :create, { reading: valid_attributes }
expect(JSON(response.body)['messages']).to eq(['Reading stored'])
end
end
context 'with invalid params' do
let(:invalid_attributes) { attributes_for(:reading).merge(data: {}) }
it 'does not create a new instance reading' do
expect {
post :create, { reading: invalid_attributes }
}.to_not change(instance.readings, :count)
end
it 'returns an unprocessable entity response' do
post :create
expect(response).to be_unprocessable
end
it 'returns an error message' do
post :create, { reading: invalid_attributes }
expect(JSON(response.body)['messages']).to eq(['Data can\'t be blank'])
end
end
context 'when reading is not given' do
it 'returns an unprocessable entity response' do
post :create
expect(response).to be_unprocessable
end
it 'returns an reading parameter required message' do
post :create
expect(JSON(response.body)['messages']).to eq(['Parameter reading is required'])
end
end
context 'when an instance with the request ip does not exist' do
before { request.env['REMOTE_ADDR'] = '1.2.3.4' }
it 'returns a not found response' do
post :create, { reading: {} }
expect(response).to be_not_found
end
it 'returns an instance not found message' do
post :create, { reading: {} }
expect(JSON(response.body)['messages']).to eq(['Instance not registered'])
end
end
end
end
|
adrian-gomez/ward-web
|
spec/controllers/dashboard_controller_spec.rb
|
require 'rails_helper'
RSpec.describe DashboardController do
describe 'GET #index' do
let!(:instance) { create(:instance) }
it 'assigns all instances as @instances' do
get :index
expect(assigns(:instances)).to eq([instance])
end
it 'returns a success response' do
get :index
expect(response).to be_success
end
it 'renders the index template' do
get :index
expect(response).to render_template(:index)
end
end
end
|
adrian-gomez/ward-web
|
spec/models/reading_spec.rb
|
require 'rails_helper'
RSpec.describe Reading do
describe 'validations' do
let(:instance) { create(:instance) }
let(:reading_attrs) { attributes_for(:reading).merge(instance: instance) }
context 'when data is empty' do
before { reading_attrs[:data] = {} }
it 'adds an error for data' do
reading = Reading.create(reading_attrs)
expect(reading.errors.keys).to eq([:data])
end
end
end
end
|
adrian-gomez/ward-web
|
config/deploy.rb
|
lock '3.5.0'
set :application, 'ward-server'
set :repo_url, '<EMAIL>:adrian-gomez/ward-web.git'
set :deploy_to, "/home/ubuntu/#{fetch(:application)}"
# Default value for :pty is false
set :pty, true
set :linked_files, fetch(:linked_files, []).push('config/mongoid.yml', 'config/secrets.yml')
set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'public/system')
set :rvm1_ruby_version, '2.2.3'
set :rvm1_alias_name, 'ward-server-ruby'
set :passenger_in_gemfile, true
set :passenger_restart_with_touch, true
|
adrian-gomez/ward-web
|
spec/views/instances/edit.html_spec.rb
|
require 'rails_helper'
RSpec.describe 'instances/edit' do
let(:instance) { create(:instance) }
before { assign(:instance, instance) }
it 'renders the edit instance form' do
render
assert_select 'form[action=?][method=?]', instance_path(instance), 'post' do
assert_select 'input[name=?][value=?]', '_method', 'patch'
assert_select 'input[name=?]', 'instance[ip]'
assert_select 'input[name=?]', 'instance[label]'
assert_select 'input[type=?]', 'submit'
end
end
end
|
adrian-gomez/ward-web
|
lib/capistrano/tasks/rvm.rake
|
namespace :rvm do
task :update_key do
on roles(fetch(:rvm1_roles, :all)) do
execute :gpg, '--keyserver hkp://keys.gnupg.net --recv-keys D39DC0E3'
end
end
task :install_bundler do
on roles(fetch(:rvm1_roles, :all)) do
execute :gem, 'install', 'bundler'
end
end
end
before 'deploy', 'rvm1:install:rvm'
before 'deploy', 'rvm1:install:ruby'
before 'deploy', 'rvm1:alias:create'
before 'deploy', 'rvm1:install:gems'
before 'rvm1:install:gems', 'rvm:install_bundler'
before 'rvm1:install:rvm', 'rvm:update_key'
|
adrian-gomez/ward-web
|
app/controllers/instances/readings_controller.rb
|
class Instances::ReadingsController < ApplicationController
before_action :set_instance
before_action :set_reading, only: [:show]
# GET /instances/:instance_id/readings
def index
readings = @instance.readings.from_last_hours(2)
render json: readings.to_json
end
# GET /instances/:instance_id/readings/:id
def show
end
private
def set_instance
@instance ||= Instance.find(params[:instance_id])
rescue Mongoid::Errors::DocumentNotFound
render json: { messages: ['Instance not found'] }, status: :not_found
end
def set_reading
@reading ||= @instance.readings.find(params[:id])
rescue Mongoid::Errors::DocumentNotFound
render json: { messages: ['Reading not found'] }, status: :not_found
end
end
|
adrian-gomez/ward-web
|
spec/controllers/instances_controller_spec.rb
|
<reponame>adrian-gomez/ward-web
require 'rails_helper'
RSpec.describe InstancesController do
describe 'GET #index' do
let!(:instance) { create(:instance) }
it 'assigns all instances as @instances' do
get :index
expect(assigns(:instances)).to eq([instance])
end
it 'returns a success response' do
get :index
expect(response).to be_success
end
it 'renders the index template' do
get :index
expect(response).to render_template(:index)
end
end
describe 'GET #show' do
let!(:instance) { create(:instance) }
it 'assigns the requested instance as @instance' do
get :show, { id: instance.id }
expect(assigns(:instance)).to eq(instance)
end
it 'returns a success response' do
get :show, { id: instance.id }
expect(response).to be_success
end
it 'renders the show template' do
get :show, { id: instance.id }
expect(response).to render_template(:show)
end
context 'when the instance does not exist' do
it 'redirects to the instances list' do
get :show, { id: 'non_existent' }
expect(response).to redirect_to(instances_url)
end
it 'sets an alert message' do
get :show, { id: 'non_existent' }
expect(flash[:alert]).to eq('Instance not found.')
end
end
end
describe 'GET #new' do
it 'assigns a new instance as @instance' do
get :new
expect(assigns(:instance)).to be_a_new(Instance)
end
it 'returns a success response' do
get :new
expect(response).to be_success
end
it 'renders the new template' do
get :new
expect(response).to render_template(:new)
end
end
describe 'GET #edit' do
let!(:instance) { create(:instance) }
it 'assigns the requested instance as @instance' do
get :edit, { id: instance.id }
expect(assigns(:instance)).to eq(instance)
end
it 'returns a success response' do
get :edit, { id: instance.id }
expect(response).to be_success
end
it 'renders the edit template' do
get :edit, { id: instance.id }
expect(response).to render_template(:edit)
end
context 'when the instance does not exist' do
it 'redirects to the instances list' do
get :edit, { id: 'non_existent' }
expect(response).to redirect_to(instances_url)
end
it 'sets an alert message' do
get :edit, { id: 'non_existent' }
expect(flash[:alert]).to eq('Instance not found.')
end
end
end
describe 'POST #create' do
context 'with valid params' do
let(:valid_attributes) { attributes_for(:instance) }
it 'creates a new Instance' do
expect {
post :create, { instance: valid_attributes }
}.to change(Instance, :count).by(1)
end
it 'redirects to the created instance' do
post :create, { instance: valid_attributes }
expect(response).to redirect_to(Instance.last)
end
it 'sets a notice message' do
post :create, { instance: valid_attributes }
expect(flash[:notice]).to eq('Instance was successfully created.')
end
end
context 'with invalid params' do
let(:invalid_attributes) { attributes_for(:instance).merge(ip: 'invalid') }
it 'does not create a new Instance' do
expect {
post :create, { instance: invalid_attributes }
}.to_not change(Instance, :count)
end
it 'returns a success response' do
post :create, { instance: invalid_attributes }
expect(response).to be_success
end
it 'assigns a newly created but unsaved instance as @instance' do
post :create, { instance: invalid_attributes }
expect(assigns(:instance)).to be_a_new(Instance)
end
it 'renders the new template' do
post :create, { instance: invalid_attributes }
expect(response).to render_template(:new)
end
end
end
describe 'PUT #update' do
let!(:instance) { create(:instance) }
context 'with valid params' do
let(:new_attributes) { { label: 'new label' } }
it 'updates the requested instance' do
expect {
put :update, { instance: new_attributes }.merge(id: instance.id).merge(id: instance.id)
instance.reload
}.to change(instance, :label).from(instance.label).to('new label')
end
it 'assigns the requested instance as @instance' do
put :update, { instance: new_attributes }.merge(id: instance.id)
expect(assigns(:instance)).to eq(instance)
end
it 'redirects to the instance' do
put :update, { instance: new_attributes }.merge(id: instance.id)
expect(response).to redirect_to(instance)
end
it 'sets a notice message' do
put :update, { instance: new_attributes }.merge(id: instance.id)
expect(flash[:notice]).to eq('Instance was successfully updated.')
end
end
context 'with invalid params' do
let(:invalid_attributes) { { ip: 'invalid' } }
it 'assigns the instance as @instance' do
put :update, { instance: invalid_attributes }.merge(id: instance.id)
expect(assigns(:instance)).to eq(instance)
end
it 'returns a success response' do
put :update, { instance: invalid_attributes }.merge(id: instance.id)
expect(response).to be_success
end
it 'renders the edit template' do
put :update, { instance: invalid_attributes }.merge(id: instance.id)
expect(response).to render_template(:edit)
end
end
context 'when the instance does not exist' do
it 'redirects to the instances list' do
put :update, { id: 'non_existent' }
expect(response).to redirect_to(instances_url)
end
it 'sets an alert message' do
put :update, { id: 'non_existent' }
expect(flash[:alert]).to eq('Instance not found.')
end
end
end
describe 'DELETE #destroy' do
let!(:instance) { create(:instance) }
it 'destroys the requested instance' do
expect {
delete :destroy, { id: instance.id }
}.to change { Instance.where(id: instance.id).exists? }.from(true).to(false)
end
it 'redirects to the instances list' do
delete :destroy, { id: instance.id }
expect(response).to redirect_to(instances_url)
end
it 'sets a notice message' do
delete :destroy, { id: instance.id }
expect(flash[:notice]).to eq('Instance was successfully destroyed.')
end
context 'when the instance does not exist' do
it 'redirects to the instances list' do
delete :destroy, { id: 'non_existent' }
expect(response).to redirect_to(instances_url)
end
it 'sets an alert message' do
delete :destroy, { id: 'non_existent' }
expect(flash[:alert]).to eq('Instance not found.')
end
end
end
end
|
adrian-gomez/ward-web
|
spec/controllers/instances/readings_controller_spec.rb
|
<reponame>adrian-gomez/ward-web
require 'rails_helper'
RSpec.describe Instances::ReadingsController do
let!(:instance) { create(:instance) }
describe 'GET #index' do
let!(:reading) { create(:reading, instance: instance) }
it 'returns a success response' do
get :index, instance_id: instance.id
expect(response).to be_success
end
it 'renders all readings of the instance' do
get :index, instance_id: instance.id
expect(response.body).to eq([reading].to_json)
end
context 'when an instance with the request ip does not exist' do
it 'returns a not found response' do
get :index, instance_id: 'non_existent'
expect(response).to be_not_found
end
it 'returns an instance not found message' do
get :index, instance_id: 'non_existent'
expect(JSON(response.body)['messages']).to eq(['Instance not found'])
end
end
end
end
|
adrian-gomez/ward-web
|
spec/factories/readings.rb
|
FactoryGirl.define do
factory :reading do
data { { disk_usage: rand * 100, cpu_usage: rand * 100,
process_list: %W[process-#{rand(1..100)}]*10 } }
instance
end
end
|
adrian-gomez/ward-web
|
app/controllers/api_controller.rb
|
class ApiController < ApplicationController
protect_from_forgery with: :null_session
rescue_from ActionController::ParameterMissing do |exception|
render json: { messages: ["Parameter #{exception.param} is required"] },
status: :unprocessable_entity
end
end
|
adrian-gomez/ward-web
|
app/controllers/reports_controller.rb
|
class ReportsController < ApplicationController
def index
@cpu_usage_rank = cpu_usage_rank
@low_disk_space = low_disk_usage
end
private
def cpu_usage_rank
Instance.all.map do |instance|
reading = instance.readings.last
next unless reading
cpu_usage = reading.data.cpu_usage
next unless cpu_usage
[instance, cpu_usage]
end.compact
.sort_by { |_, cpu_usage| cpu_usage }
.reverse
end
def low_disk_usage
Instance.all.map do |instance|
reading = instance.readings.last
next unless reading
disk_usage = reading.data.disk_usage
next unless disk_usage
[instance, disk_usage]
end.compact
.select { |_, disk_usage| disk_usage > 90 }
.sort_by { |_, disk_usage| disk_usage }
end
end
|
adrian-gomez/ward-web
|
app/controllers/api/readings_controller.rb
|
class Api::ReadingsController < ApiController
before_action :set_instance, only: [:create]
# POST /api/readings
def create
instance = Reading.create(reading_params)
if instance.persisted?
render json: { messages: ['Reading stored'], actions: [] }
else
render json: { messages: instance.errors.full_messages }, status: :unprocessable_entity
end
end
private
def set_instance
@instance ||= Instance.find_by!(ip: request.remote_ip)
rescue Mongoid::Errors::DocumentNotFound
render json: { messages: ['Instance not registered'] }, status: :not_found
end
def reading_params
params.require(:reading).permit!.merge(instance: @instance)
end
end
|
adrian-gomez/ward-web
|
app/models/reading_data.rb
|
<filename>app/models/reading_data.rb
class ReadingData
include Mongoid::Document
include Mongoid::Attributes::Dynamic
field :cpu_usage, type: Float
field :disk_usage, type: Float
embedded_in :reading
end
|
adrian-gomez/ward-web
|
spec/rails_helper.rb
|
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
abort('The Rails environment is running in production mode!') if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
RSpec.configure do |config|
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
config.before(:suite) do
DatabaseCleaner.strategy = :truncation
DatabaseCleaner.clean_with(:truncation)
end
config.around(:each) do |example|
DatabaseCleaner.cleaning do
example.run
end
end
end
|
adrian-gomez/ward-web
|
app/helpers/instances_helper.rb
|
module InstancesHelper
def instance_title(instance)
if instance.label.present?
"#{instance.label} [#{instance.ip}]"
else
"#{instance.ip}"
end
end
end
|
adrian-gomez/ward-web
|
config/routes.rb
|
<reponame>adrian-gomez/ward-web
Rails.application.routes.draw do
get :dashboard, controller: :dashboard, action: :index
get :reports, controller: :reports, action: :index
resources :instances do
resources :readings, only: [:index, :show], controller: 'instances/readings'
end
namespace :api, defaults: { format: :json } do
resources :readings, only: [:create]
end
root 'dashboard#index'
end
|
adrian-gomez/ward-web
|
spec/controllers/reports_controller_spec.rb
|
<gh_stars>0
require 'rails_helper'
RSpec.describe ReportsController do
describe 'GET #index' do
let!(:instance) { create(:instance) }
it 'assigns the cpu usage rank as @cpu_usage_rank' do
get :index
expect(assigns(:cpu_usage_rank)).to be
end
it 'assigns the instances with log disk space as @low_disk_space' do
get :index
expect(assigns(:low_disk_space)).to be
end
it 'returns a success response' do
get :index
expect(response).to be_success
end
it 'renders the index template' do
get :index
expect(response).to render_template(:index)
end
end
end
|
adrian-gomez/ward-web
|
config/deploy/production.rb
|
server 'ec2-54-187-76-110.us-west-2.compute.amazonaws.com', user: 'ubuntu', roles: %w{app db web}
|
adrian-gomez/ward-web
|
app/controllers/dashboard_controller.rb
|
<reponame>adrian-gomez/ward-web
class DashboardController < ApplicationController
def index
@instances = Instance.all
end
end
|
adrian-gomez/ward-web
|
spec/models/instance_spec.rb
|
<filename>spec/models/instance_spec.rb
require 'rails_helper'
RSpec.describe Instance do
describe 'validations' do
let(:instance_attrs) { attributes_for(:instance) }
context 'when the ip is empty' do
before { instance_attrs[:ip] = '' }
it 'adds an error for ip' do
instance = Instance.create(instance_attrs)
expect(instance.errors.keys).to eq([:ip])
end
end
context 'when the ip is invalid' do
before { instance_attrs[:ip] = 'invalid' }
it 'adds an error for ip' do
instance = Instance.create(instance_attrs)
expect(instance.errors.keys).to eq([:ip])
end
end
end
end
|
adrian-gomez/ward-web
|
spec/helpers/instances_helper_spec.rb
|
<reponame>adrian-gomez/ward-web<gh_stars>0
require 'rails_helper'
RSpec.describe InstancesHelper do
describe '#instance_title' do
let(:instance) { create(:instance, ip: '127.1.1.4') }
context 'when the instance has a label' do
before { instance.label = 'some label' }
it 'returns the label and the ip address of the instance' do
expect(helper.instance_title(instance)).to eq('some label [127.1.1.4]')
end
end
context 'when the instance does not have a label' do
before { instance.label = '' }
it 'returns the ip address of the instance' do
expect(helper.instance_title(instance)).to eq('127.1.1.4')
end
end
end
end
|
adrian-gomez/ward-web
|
app/controllers/instances_controller.rb
|
class InstancesController < ApplicationController
before_action :set_instance, only: [:show, :edit, :update, :destroy]
# GET /instances
def index
@instances = Instance.all
end
# GET /instances/1
def show
end
# GET /instances/new
def new
@instance = Instance.new
end
# GET /instances/1/edit
def edit
end
# POST /instances
def create
@instance = Instance.new(instance_params)
if @instance.save
redirect_to @instance, notice: 'Instance was successfully created.'
else
render :new
end
end
# PATCH/PUT /instances/1
def update
if @instance.update(instance_params)
redirect_to @instance, notice: 'Instance was successfully updated.'
else
render :edit
end
end
# DELETE /instances/1
def destroy
@instance.destroy
redirect_to instances_url, notice: 'Instance was successfully destroyed.'
end
private
def set_instance
@instance = Instance.find(params[:id])
rescue Mongoid::Errors::DocumentNotFound
redirect_to instances_path, alert: 'Instance not found.'
end
def instance_params
params.require(:instance).permit(:ip, :label)
end
end
|
adrian-gomez/ward-web
|
spec/views/instances/new.html_spec.rb
|
<gh_stars>0
require 'rails_helper'
RSpec.describe 'instances/new' do
let(:instance) { Instance.new }
before { assign(:instance, instance) }
it 'renders the new instance form' do
render
assert_select 'form[action=?][method=?]', instances_path, 'post' do
assert_select 'input[name=?]', 'instance[ip]'
assert_select 'input[name=?]', 'instance[label]'
assert_select 'input[type=?]', 'submit'
end
end
end
|
bkayes/home
|
_plugins/jsonfeed.rb
|
<filename>_plugins/jsonfeed.rb
module Jekyll
class JSONFeedFile < StaticFile
def initialize(site, base, dir, name, docs)
super(site, site.source, dir, name)
@docs = docs
end
def feed_data()
markdown = @site.find_converter_instance(Jekyll::Converters::Markdown)
smart = @site.find_converter_instance(Jekyll::Converters::SmartyPants)
items = @docs.reverse.map do |doc|
docurl = @site.config['url'] + doc.url
{
:id => docurl,
:url => docurl,
:title => smart.convert(doc.data['title']),
:content_html => doc.content,
:summary => markdown.convert(doc.data['excerpt']),
:date_published => doc.date.to_datetime.rfc3339,
}
end
{
:version => "https://jsonfeed.org/version/1",
:title => @site.config['name'],
:home_page_url => @site.config['url'],
:feed_url => @site.config['url'] + @dir + @name,
:author => {
:name => @site.config['author'],
:url => @site.config['url'],
},
:items => items,
}
end
def write(dest)
dest_path = destination(dest)
FileUtils.mkdir_p(File.dirname(dest_path))
File.open(dest_path, "w") do |f|
f.write JSON.pretty_generate(feed_data())
# uglier: f.write feed_data().to_json
end
end
end
class JSONFeedGenerator < Generator
safe true
priority :low
def generate(site)
file = JSONFeedFile.new(site, site.source, "/", "feed.json",
site.collections["posts"].docs)
site.static_files << file
end
end
end
|
rickytan/RTBlockCallChecker
|
RTBlockCallChecker.podspec
|
<reponame>rickytan/RTBlockCallChecker
#
# Be sure to run `pod lib lint RTBlockCallChecker.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'RTBlockCallChecker'
s.version = '0.1.2'
s.summary = 'A helper utility to check if a block has been called'
s.description = <<-DESC
This project provide a tricky way to check if a block passed to a method has been
called.
DESC
s.homepage = 'https://github.com/rickytan/RTBlockCallChecker'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'rickytan' => '<EMAIL>' }
s.source = { :git => 'https://github.com/rickytan/RTBlockCallChecker.git', :tag => s.version.to_s }
s.ios.deployment_target = '8.0'
s.requires_arc = true
s.source_files = 'RTBlockCallChecker/Classes/**/*'
s.frameworks = 'Foundation'
end
|
uk-gov-mirror/alphagov.search-admin
|
features/step_definitions/update_search_index_on_best_bet_change_steps.rb
|
Then(/^the query should have been sent to the metasearch index$/) do
check_search_api_was_sent_an_exact_best_bet_document(Query.last)
end
Then(/^the remaining merged best bets should have been sent to the metasearch index$/) do
check_search_api_was_sent_an_exact_best_bet_document(Query.last)
end
Then(/^the best bets should have been deleted in the metasearch index$/) do
check_search_api_was_sent_a_best_bet_delete(@query_es_ids)
end
|
uk-gov-mirror/alphagov.search-admin
|
app/mailers/application_mailer.rb
|
<gh_stars>1-10
class ApplicationMailer < Mail::Notify::Mailer
default from: proc { no_reply_email_address }
def no_reply_email_address
name = "GOV.UK publishing"
if GovukAdminTemplate.environment_label !~ /production/i
name.prepend("[GOV.UK #{GovukAdminTemplate.environment_label}] ")
end
address = Mail::Address.new("<EMAIL>")
address.display_name = name
address.format
end
def template_id
@template_id ||= ENV.fetch("GOVUK_NOTIFY_TEMPLATE_ID", "fake-test-template-id")
end
end
|
uk-gov-mirror/alphagov.search-admin
|
app/models/elastic_search_recommended_link.rb
|
class ElasticSearchRecommendedLink
delegate :format, :link, :title, :description, to: :recommended_link
def initialize(recommended_link)
@recommended_link = recommended_link
end
def body
{
link: link,
details: details.to_json,
}
end
def details
{
title: title,
link: link,
description: description,
format: format,
indexable_content: indexable_content,
}
end
def id
link
end
def indexable_content
recommended_link.keywords
end
private
attr_reader :recommended_link
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.