text stringlengths 10 2.61M |
|---|
module Endpoints
class Medias < Grape::API
resource :medias do
# test medias api
get :ping do
{success: "Media Endpoints"}
end
# Get all media
# GET: /api/v1/medias
# parameters:
# token String *required
get do
user = User.find_by_auth_token(params[:token])
if user.present?
medias = user.medias
info = medias.map{|m| {id:m.id.to_s, filename:m.media_url, thumb:m.thumb_url, type:m.media_type, user_time:user.time.strftime("%Y-%m-%d %H:%M:%S"), user_id:user.id.to_s,created_at:media.created_time(user.time_zone)}}
{data:info,message:{type:'success',value:'get all medias', code:TimeChatNet::Application::SUCCESS_QUERY}}
else
{data:[],message:{type:'error',value:'Can not find this user', code:TimeChatNet::Application::ERROR_LOGIN}}
end
end
# Get all shared media
# GET: /api/v1/medias/shared_medias
# parameters:
# token String *required
get :shared_medias do
user = User.find_by_auth_token(params[:token])
if user.present?
medias = Medium.shared_medias(user).map{|m| {id:m.id.to_s, media:m.media_url, owner_id:m.user.id.to_s}}
{data:medias,message:{type:'success',value:'get all medias', code:TimeChatNet::Application::SUCCESS_QUERY}}
else
{data:[],message:{type:'error',value:'Can not find this user', code:TimeChatNet::Application::ERROR_LOGIN}}
end
end
# Get media info by media id
# GET: /api/v1/medias/media_info
# parameters:
# token String *required
# media_id String *required
get :media_info do
user = User.find_by_auth_token(params[:token])
media_id = params[:media_id]
if user.present?
media = Medium.find(media_id)
info = [{id:media.id.to_s, filename:media.media_url, thumb:media.thumb_url, type:media.media_type, user_time:user.time.strftime("%Y-%m-%d %H:%M:%S"), user_id:user.id.to_s,created_at:media.created_time(user.time_zone)}]
{data:info,message:{type:'success',value:'get all medias', code:TimeChatNet::Application::SUCCESS_QUERY}}
else
{data:[],message:{type:'error',value:'Can not find this user', code:TimeChatNet::Application::ERROR_LOGIN}}
end
end
# Get media for period
# GET: /api/v1/medias/media_for_period
# parameters:
# token String *required
# hour String *required
get :media_for_period do
user = User.find_by_auth_token(params[:token])
if user.present?
if params[:hour].present?
hour = params[:hour].to_i - user.time_zone.to_i
medias = user.medias.medias_by_time(hour)
else
medias = user.medias
end
info = medias.map{|m| {id:m.id.to_s, filename:m.media_url, thumb:m.thumb_url, type:m.media_type, user_time:user.time.strftime("%Y-%m-%d %H:%M:%S"), user_id:user.id.to_s,created_at:m.created_at.strftime("%Y-%m-%d %H:%M:%S")}}
{data:info,message:{type:'success',value:'get all medias', code:TimeChatNet::Application::SUCCESS_QUERY}}
else
{data:[],message:{type:'error',value:'Can not find this user', code:TimeChatNet::Application::ERROR_LOGIN}}
end
end
# Get medias for friend
# GET: /api/v1/medias/medias_for_friend
# parameters:
# token String *required
# friend_id String *required
get :medias_for_friend do
user = User.find_by_auth_token(params[:token])
friend = User.find(params[:friend_id])
if user.present?
timezone = friend.time_zone.to_i
friend_time = Time.now + timezone.hour
friend.clear_media
st_date = DateTime.new(friend_time.year,friend_time.month,friend_time.day) - timezone.hour
medias = friend.medias.where(:created_at.gte => st_date).order("created_at ASC")
info = medias.map{|m| {id:m.id.to_s, filename:m.media_url, thumb:m.thumb_url, type:m.media_type, user_time:user.time.strftime("%Y-%m-%d %H:%M:%S"), user_id:user.id.to_s,created_at:m.created_time(user.time_zone)}}
{data:info,message:{type:'success',value:'get all medias', code:TimeChatNet::Application::SUCCESS_QUERY}}
else
{data:[],message:{type:'error',value:'Can not find this user', code:TimeChatNet::Application::ERROR_LOGIN}}
end
end
# Upload new media
# POST: /api/v1/medias/upload
# parameters:
# token String *required
# media Image Data
# media_type String *required [photo, video]
# video_thumb Image Data
post :upload do
user = User.find_by_auth_token(params[:token])
media = params[:media]
video_thumb = params[:video_thumb]
media_type = params[:media_type]
if user.present?
if media_type == '1'
media = user.medias.build(file:media, media_type:media_type)
else
media = user.medias.build(file:media, media_type:media_type, video_thumb:video_thumb)
end
if media.save
{data:{id:media.id.to_s,filename:media.media_url},message:{type:'success',value:'success uploaded', code:TimeChatNet::Application::SUCCESS_UPLOADED}}
else
{data:media.errors.messages,message:{type:'error',value:'Can not create this media', code:TimeChatNet::Application::ERROR_LOGIN}}
end
else
{data:[],message:{type:'error',value:'Can not find this user', code:TimeChatNet::Application::ERROR_LOGIN}}
end
end
# Update media
# POST: /api/v1/medias/update
# parameters:
# token String *required
# media_id String *required
# media Image Data
post :update do
user = User.find_by_auth_token(params[:token])
media = params[:media]
media_id = params[:media_id]
if user.present?
media = user.medias.find(media_id)
media.update_attributes(file:media)
{data:{id:media.id.to_s,media:media.media_url},message:{type:'success',value:'Update media', code:TimeChatNet::Application::SUCCESS_UPLOADED}}
else
{data:[],message:{type:'error',value:'Can not find this user', code:TimeChatNet::Application::ERROR_LOGIN}}
end
end
# Share media
# POST: /api/v1/medias/share
# parameters:
# token String *required
# media_id String *required
# friend_id String *required
post :share do
user = User.find_by_auth_token(params[:token])
media_id = params[:media_id]
friend = User.find(params[:friend_id])
if user.present?
media = Medium.find(media_id)
if media.present?
media.share(friend)
{data:{id:media.id.to_s,media:media.media_url},message:{type:'success',value:'Shared Media', code:TimeChatNet::Application::SUCCESS_UPLOADED}}
else
{data:[],message:{type:'error',value:'Can not find media', code:TimeChatNet::Application::MEDIA_NOT_FOUND}}
end
else
{data:[],message:{type:'error',value:'Can not find this user', code:TimeChatNet::Application::ERROR_LOGIN}}
end
end
# Share medias
# POST: /api/v1/medias/share_medias
# parameters:
# token String *required
# type Integer
# media_id String *required
# friend_ids String *required
post :share_medias do
user = User.find_by_auth_token(params[:token])
if user.present?
friends = User.in(id:params[:friend_ids].split(","))
media = Medium.find(params[:media_id])
if media.present?
media.share_friends(user,friends)
{data:{id:media.id.to_s,media:media.media_url},message:{type:'success',value:'Shared Media', code:TimeChatNet::Application::SUCCESS_UPLOADED}}
else
{data:[],message:{type:'error',value:'Can not find media', code:TimeChatNet::Application::MEDIA_NOT_FOUND}}
end
else
{data:[],message:{type:'error',value:'Can not find this user', code:TimeChatNet::Application::ERROR_LOGIN}}
end
end
# Get like
# GET: /api/v1/medias/like
# parameters:
# token String *required
# media_id String *required
get :like do
user = User.find_by_auth_token(params[:token])
media_id = params[:media_id]
if user.present?
media = Medium.find(media_id)
if media.present?
likes = media.likes
{data:{count:likes.count},message:{type:'success',value:'added like', code:TimeChatNet::Application::SUCCESS_QUERY}}
else
{data:{count:0},message:{type:'error',value:'Can not find media', code:TimeChatNet::Application::MEDIA_NOT_FOUND}}
end
else
{data:[],message:{type:'error',value:'Can not find this user', code:TimeChatNet::Application::ERROR_LOGIN}}
end
end
# Send like
# POST: /api/v1/medias/like
# parameters:
# token String *required
# media_id String *required
post :like do
user = User.find_by_auth_token(params[:token])
media_id = params[:media_id]
if user.present?
media = Medium.find(media_id)
if media.present?
like = media.likes.build(user:user)
likes = media.likes
if like.save
{data:{count:likes.count},message:{type:'success',value:'added like', code:TimeChatNet::Application::SUCCESS_QUERY}}
else
{data:{count:likes.count},message:{type:'error',value:like.errors.full_messages.first, code:TimeChatNet::Application::SUCCESS_QUERY}}
end
else
{data:[],message:{type:'error',value:'Can not find media', code:TimeChatNet::Application::MEDIA_NOT_FOUND}}
end
else
{data:[],message:{type:'error',value:'Can not find this user', code:TimeChatNet::Application::ERROR_LOGIN}}
end
end
# Get media info and post media
# POST: /api/v1/medias/main_page_info
# parameters:
# token String *required
# media_id String *required
# media_exist Boolean
# media_type String
# video_thumb String
# media String
post :main_page_info do
user = User.find_by_auth_token(params[:token])
media_id = params[:media_id]
media_exist = params[:media_exist]
media_type = params[:media_type]
video_thumb = params[:video_thumb]
media = params[:media]
if user.present?
if media_exist == '1'
if media_type == '1'
media = user.medias.build(file:media, media_type:media_type)
else
media = user.medias.build(file:media, media_type:media_type, video_thumb:video_thumb)
end
if media.save
{data:{id:media.id.to_s,filename:media.media_url, created_at:media.created_time(user.time_zone), like_count:0, comment_count:0, notification_count:user.unread_notifications.count}, message:{type:'success',value:'success uploaded', code:TimeChatNet::Application::SUCCESS_UPLOADED}}
else
{data:media.errors.full_messages.first,message:{type:'error',value:'Can not create this media', code:TimeChatNet::Application::ERROR_LOGIN}}
end
else
media = Medium.where(id:params[:media_id]).first
likes = media.present? ? media.likes.count : 0
comments = media.present? ? media.comments.count : 0
filename = media.media_type == '0' ? media.thumb_url : media.media_url
{data:{id:media.id.to_s,filename:filename, created_at:media.created_time(user.time_zone), like_count:likes, comment_count:comments, notification_count:user.unread_notifications.count}, message:{type:'success',value:'success query', code:TimeChatNet::Application::SUCCESS_QUERY}}
end
else
{data:[],message:{type:'error',value:'Can not find this user', code:TimeChatNet::Application::ERROR_LOGIN}}
end
end
# Destroy media
# POST: /api/v1/medias/destroy_media
# parameters:
# token String *required
# media_id String *required
post :destroy_media do
user = User.find_by_auth_token(params[:token])
media_id = params[:media_id]
if user.present?
media = Medium.find(media_id)
if media.destroy
{data:[], message:{type:'success',value:"Destroyed media", code: TimeChatNet::Application::SUCCESS_QUERY}}
else
{data:[], message:{type:'error',value:"Can not destroy this media", code: TimeChatNet::Application::ERROR_QUERY}}
end
else
{data:[],message:{type:'error',value:'Can not find this user', code:TimeChatNet::Application::ERROR_LOGIN}}
end
end
end #end medias
end
end
|
module ProfileBaseHelper
def link_to_profile_controller(user, profile_mode = nil, controller = nil, url_opts = nil, html_opts = nil)
profile_mode ||= :aboutme
controller ||= 'profile_home'
url_opts ||= {}
url_opts[:controller] ||= controller
url_opts[:profile_mode] ||= profile_mode
url_opts[:screen_name] ||= user.screen_name
html_opts ||= {}
link_text = url_opts[:link_text] || 'Public Profile'
link_to(link_text, url_opts.reject {|n,v| n == :link_text}, html_opts)
end
def profile_sub_tab2(tab)
if ("profile_#{tab}" == params[:controller]) ||
(params[:controller] == 'profile_home' && tab == 'profile') ||
(params[:controller] == 'profile_my_home' && tab == 'my_home')
return highlighted_profile_tab(tab)
end
if tab == 'profile'
link_to_profile_home @user, @profile_mode, { :link_text => 'Profile' }
elsif ['reviews', 'friends_and_fans', 'photos', 'blog'].include?(tab)
# hide any blank tabs
return if tab == 'reviews' && aboutme? && @user.stat.reviews_written.to_i == 0
return if tab == 'friends_and_fans' && aboutme? && @user.stat.friends.to_i == 0 && @user.stat.fans.to_i == 0
return if tab == 'photos' && aboutme? && @user.photos.gallery.size == 0 && Review.count_reviews_by_user_with_photos(@user) == 0
return if tab == 'blog' && aboutme? && @user.scribbles.count == 0
self.send "link_to_profile_#{tab}", @user, @profile_mode, { :page => nil }
elsif aboutme?
nil
elsif tab == 'my_home'
link_to_my_home @user, nil
else
self.send "link_to_my_home_#{tab}", @user, { :page => nil }
end
end
def highlighted_profile_tab(tab)
text = tab.titleize
text.gsub!(/ And /, ' & ')
text = 'more…' if tab == 'more'
"<span class=\"text_bold highlighted_profile_tab\">#{text}</span>"
end
def build_profile_crumbs
crumbs = []
if aboutme?
crumbs << ['Community', community_url]
crumbs << [@user.screen_name, profile_url(:screen_name => @user.screen_name)]
else
crumbs << ['My Home', my_home_url]
end
name = params['controller'].gsub(/^profile_(.*)$/) { |s| $1.titleize }
name.gsub!(/ And /, ' & ')
name = 'Friends\' Activity' if name == 'Friends Activity'
name = 'more…' if name == 'More'
unless (name == 'Home' && aboutme?) || name == 'My Home'
name = 'Edit Profile' if name == 'Home'
crumbs << [name, { :profile_mode => @profile_mode, :screen_name => @user.screen_name, :controller => "/#{params['controller']}" }]
end
crumbs += @extra_profile_crumbs unless @extra_profile_crumbs.blank?
crumbs
end
def link_to_profile(user, profile_mode = nil, url_opts = nil, html_opts = nil)
url_opts ||= {}
url_opts[:link_text] ||= 'Public Profile'
link_to_profile_controller user, profile_mode, 'profile_home',
url_opts, html_opts
end
def link_to_profile_home(user, profile_mode = nil, url_opts = nil, html_opts = nil)
url_opts ||= {}
url_opts[:link_text] ||= 'Home'
link_to_profile_controller user, profile_mode, 'profile_home',
url_opts, html_opts
end
def link_to_profile_reviews(user, profile_mode = nil, url_opts = nil, html_opts = nil)
url_opts ||= {}
url_opts[:link_text] ||= 'Reviews'
link_to_profile_controller user, profile_mode, 'profile_reviews',
url_opts, html_opts
end
def link_to_profile_friends_and_fans(user, profile_mode = nil, url_opts = nil, html_opts = nil)
url_opts ||= {}
url_opts[:link_text] ||= 'Friends & Fans'
link_to_profile_controller user, profile_mode,
'profile_friends_and_fans', url_opts, html_opts
end
def link_to_profile_photos(user, profile_mode = nil, url_opts = nil, html_opts = nil)
url_opts ||= {}
url_opts[:link_text] ||= 'Photos'
link_to_profile_controller user, profile_mode, 'profile_photos', url_opts,
html_opts
end
def link_to_profile_blog(user, profile_mode = nil, url_opts = nil, html_opts = nil)
url_opts ||= {}
url_opts[:link_text] ||= 'Blog'
link_to_profile_controller user, profile_mode, 'profile_blog', url_opts,
html_opts
end
def link_to_my_home(user, url_opts = nil, html_opts = nil)
url_opts ||= {}
url_opts[:link_text] ||= 'My Home'
link_to url_opts[:link_text], my_home_url(url_opts.reject {|n,v| n == :link_text}), html_opts
end
def link_to_my_home_about_me(user, url_opts = nil, html_opts = nil)
url_opts ||= {}
url_opts[:link_text] ||= 'About Me'
link_to_profile_controller user, :my_home, 'profile_about_me', url_opts,
html_opts
end
def link_to_my_home_inbox(user, url_opts = nil, html_opts = nil)
url_opts ||= {}
url_opts[:link_text] ||= 'Inbox'
link_to_profile_controller user, :my_home, 'profile_inbox', url_opts,
html_opts
end
def link_to_my_home_friends_activity(user, url_opts = nil, html_opts = nil)
url_opts ||= {}
url_opts[:link_text] ||= 'Friends\' Activity'
link_to_profile_controller user, :my_home, 'profile_friends_activity',
url_opts, html_opts
end
def link_to_my_home_stats(user, url_opts = nil, html_opts = nil)
url_opts ||= {}
url_opts[:link_text] ||= 'Stats'
link_to_profile_controller user, :my_home, 'profile_stats', url_opts,
html_opts
end
def link_to_my_home_email_settings(user, url_opts = nil, html_opts = nil)
url_opts ||= {}
url_opts[:link_text] ||= 'Email Settings'
link_to_profile_controller user, :my_home, 'profile_email_settings',
url_opts, html_opts
end
def link_to_my_home_account_info(user, url_opts = nil, html_opts = nil)
url_opts ||= {}
url_opts[:link_text] ||= 'Account Info'
link_to_profile_controller user, :my_home, 'profile_account_info',
url_opts, html_opts
end
def link_to_my_home_password(user, url_opts = nil, html_opts = nil)
url_opts ||= {}
url_opts[:link_text] ||= 'Password'
link_to_profile_controller user, :my_home, 'profile_password', url_opts,
html_opts
end
def link_to_my_home_manage_i_am(user, url_opts = nil, html_opts = nil)
url_opts ||= {}
url_opts[:link_text] ||= 'Manage I Am'
link_to_profile_controller user, :my_home, 'profile_manage_i_am', url_opts,
html_opts
end
def link_to_my_home_interests(user, url_opts = nil, html_opts = nil)
url_opts ||= {}
url_opts[:link_text] ||= 'Interests'
link_to_profile_controller user, :my_home,
'profile_interests', url_opts, html_opts
end
def link_to_my_home_settings(user, url_opts = nil, html_opts = nil)
url_opts ||= {}
url_opts[:link_text] ||= 'Settings'
link_to_profile_controller user, :my_home,
'profile_settings', url_opts, html_opts
end
def link_to_my_home_more(user, url_opts = nil, html_opts = nil)
url_opts ||= {}
url_opts[:link_text] ||= 'more…'
link_to_profile_controller user, :my_home,
'profile_more', url_opts, html_opts
end
def profile_dimension_link(dim_config, expanded=dim_config.expanded)
link_to_function((dim_config.image) ? image_tag(dim_config.image) : h(dim_config.name), "show_more(this, { toggleElement: 'dim_#{dim_config.name}', toggledIconClass: 'cue_down' })",
{ :class => "text_bold float_left cue_#{navigation_dimension_arrow(expanded)}" })
end
def profile_dimension_value_link(dim_val, params, total_num_recs = nil)
count = dim_val.properties['DGraph.Bins']
count = 'all' if count.to_i == total_num_recs.to_i
text = h dim_val.dim_value_name
if count == 'all'
return '<div class="add_null_sm">' + text + ' <span>(all)</span></div>'
end
link = link_to_profile_dimension_value dim_val, nil, text, Hash[params].symbolize_keys,
{ :title => dim_val.dim_value_name }
if dim_val.properties && dim_val.properties['DGraph.Bins']
link += " <span>(#{count})</span>"
end
return link
end
def link_to_profile_dimension_value(dim_val, user = nil, text = nil, url_opts = nil, html_opts = nil)
user ||= @user
text ||= dim_val.dim_value_name
url_opts ||= { :profile_mode => @profile_mode, :screen_name => user.screen_name, :controller => 'profile_reviews'}
n_param = strip_primary_dim(hash_from_query_string(dim_val.selection_link)[:N])
url_opts.merge!(:N => n_param)
link_to text, url_for(url_opts), html_opts
end
def profile_breadcrumb_dimension_value_link(dim_val, params, url_opts = nil)
url_opts = url_opts.blank? ? {} : url_opts.clone
url_opts.merge! Hash[params].symbolize_keys
n_param = strip_primary_dim(hash_from_query_string(dim_val.removal_link)[:N])
if n_param.blank?
url_opts.delete(:N)
else
url_opts.merge! :N => n_param
end
cat = Category.find_by_dim_value_id dim_val['dim_value_id'].to_s
if cat && cat != cat.find_top_level
link_to h(cat.name), profile_reviews_url_from_opts(url_opts),
{ :class => 'checked_sm add_with_text back_sm_hover' }
else
text = url_opts[:text] || dim_val.dim_value_name
url_opts.delete(:text)
link_to h(text), profile_reviews_url_from_opts(url_opts),
{ :class => 'checked_sm add_with_text delete_sm_hover' }
end
end
def profile_dimension_select_multiple_link(dimension, params, max_dim_vals=101)
url_opts = params.merge(:action => 'show_more_dim_values',
:Xrc => "id+#{dimension.dimension_id}+dynrank+disabled+dynorder+static+dyncount+#{max_dim_vals}",:dim_name => dimension.dimension_name
)
link_to_remote 'more »', { :url => url_opts, :loading => "create_custom_lightbox({ width:480, height:330 })" }, {:class => 'margin_20_left text_bold'}
end
def profile_page_sort_link(cur_sort, text, field, default_direction)
direction = if cur_sort.blank? || !cur_sort.starts_with?(field)
default_direction
else
(cur_sort.ends_with?("0") ? "1" : "0")
end
arrow_direction = case(field)
when 'score'
(direction == '0') ? 'down' : 'up'
when 'date'
(direction == '0') ? 'down' : 'up'
when 'stars'
(direction == '0') ? 'up' : 'down'
end
url_opts = Hash[params].symbolize_keys.merge :sort => "#{field}-#{direction}"
url_opts.delete :page
link_to_function text,
"document.location.href = '#{profile_reviews_url_from_opts(url_opts)}';",
:class => "#{(cur_sort && cur_sort.starts_with?(field)) ? "text_bold cue_#{arrow_direction}" : ''}"
end
# decides which builtin foo_url method based on value of opts[:profile_mode]
def profile_reviews_url_from_opts(opts)
(opts[:profile_mode] == :my_home ? profile_reviews_my_home_url(opts) : profile_reviews_about_me_url(opts))
end
def profile_page_items_per_page_link(cur_per_page, per_page, text = nil)
if per_page == cur_per_page
"<strong>#{text || per_page}</strong>"
else
link_to(per_page, url_for(Hash[params].symbolize_keys.merge(:per_page => per_page, :page => 1)))
end
end
def suggest_a_friend_link
%{
<div id="suggest_a_friend" class="suggest_a_friend">
<a href="#" onclick="new SecureFunction(link_to_suggest_a_friend('#{ url_for(suggest_a_friend_url(:to_user => @user.screen_name)) }')); return false;" class="call_to_action">recommend a new friend to #{ truncate_username(@user.screen_name) }</a>
<script>
function link_to_suggest_a_friend(url){
create_custom_lightbox({width:570, height:500, url:url});
}
</script>
</div>
}
end
def strip_primary_dim(n)
return n if n.blank?
n_ary = n.split(' ')
n_ary.delete(ENDECA_PRIMARY_DIM_ID.to_s)
n_ary.join(' ')
end
def excerpt(text, limit)
return "" unless text
lines_to_display = []
n = 0
text.each_line do |line|
logger.info "line -- n = #{n.to_s}"
if n < limit
lines_to_display << (line.length > limit ? limit_text(line, limit - n) : line)
else
break
end
n += [line.length, 72].max
end
[lines_to_display.join("\n"), n >= limit]
end
def link_to_secure_lightbox(anchor_text, url)
# Note: please do not add arguments to customize the height and width
# Instead, let's customize these in the CSS!
# Let's name or id these, and use CSS declarations instead.
%{
<a onclick="new SecureFunction(function(){
create_custom_lightbox({
width:570,
height:500,
url: '#{url}'
});
});
return false;"
href="#">#{anchor_text}</a>
}
end
def edit_fun_facts_url
url_for :secure => App.secure?, :controller => 'profile_answers', :action => 'edit', :profile_mode => :my_home, :screen_name => @user.screen_name
end
def edit_motto_url
url_for :secure => App.secure?, :controller => 'profile_answers', :action => 'edit_motto', :profile_mode => :my_home, :screen_name => @user.screen_name
end
end
|
require 'logger'
module Raven
module Breadcrumbs
module SentryLogger
LEVELS = {
::Logger::DEBUG => 'debug',
::Logger::INFO => 'info',
::Logger::WARN => 'warn',
::Logger::ERROR => 'error',
::Logger::FATAL => 'fatal'
}.freeze
def add(*args)
add_breadcrumb(*args)
super
end
def add_breadcrumb(severity, message = nil, progname = nil)
message = progname if message.nil? # see Ruby's Logger docs for why
return if ignored_logger?(progname)
return if message.nil? || message == ""
# some loggers will add leading/trailing space as they (incorrectly, mind you)
# think of logging as a shortcut to std{out,err}
message = message.to_s.strip
last_crumb = Raven.breadcrumbs.peek
# try to avoid dupes from logger broadcasts
if last_crumb.nil? || last_crumb.message != message
Raven.breadcrumbs.record do |crumb|
crumb.level = Raven::Breadcrumbs::SentryLogger::LEVELS.fetch(severity, nil)
crumb.category = progname || 'logger'
crumb.message = message
crumb.type =
if severity >= 3
"error"
else
crumb.level
end
end
end
end
private
def ignored_logger?(progname)
progname == "sentry" ||
Raven.configuration.exclude_loggers.include?(progname)
end
end
module OldBreadcrumbsSentryLogger
def self.included(base)
base.class_eval do
include Raven::Breadcrumbs::SentryLogger
alias_method :add_without_raven, :add
alias_method :add, :add_with_raven
end
end
def add_with_raven(*args)
add_breadcrumb(*args)
add_without_raven(*args)
end
end
end
end
Raven.safely_prepend(
"Breadcrumbs::SentryLogger",
:from => Raven,
:to => ::Logger
)
|
class Triptrack < ActiveRecord::Base
attr_accessible :name, :location, :latitude, :longitude, :clip, :address,
:description
has_attached_file :clip
belongs_to :user
class << self
def within_box(north, south, east, west)
sw_string = "(#{west}, #{south})"
ne_string = "(#{east}, #{north})"
box_string = "box '(#{sw_string}, #{ne_string})'"
where("location <@ #{box_string}")
end
end
def latitude
location.y if location
end
def longitude
location.x if location
end
def latitude=(lat)
ensure_location
location.y = lat.to_f
end
def longitude=(lng)
ensure_location
location.x = lng.to_f
end
def as_json(arg=nil)
{
"id" => id,
"name" => name,
"address" => address,
"latitude" => latitude,
"longitude" => longitude,
"description" => description,
"clip_url" => clip.url
}
end
private
def ensure_location
self.location = Point.new unless location
end
end |
require File.join(File.dirname(__FILE__), 'spec_helper')
require 'barby/outputter/prawn_outputter'
include Barby
describe PrawnOutputter do
before :each do
@barcode = Barcode.new
def @barcode.encoding; '10110011100011110000'; end
@outputter = PrawnOutputter.new(@barcode)
end
it "should register to_pdf and annotate_pdf" do
Barcode.outputters.should include(:to_pdf)
Barcode.outputters.should include(:annotate_pdf)
end
it "should have a to_pdf method" do
@outputter.should respond_to(:to_pdf)
end
it "should return a PDF document in a string on to_pdf" do
@barcode.to_pdf.should be_an_instance_of(String)
end
it "should return the same Prawn::Document on annotate_pdf" do
doc = Prawn::Document.new
@barcode.annotate_pdf(doc).object_id.should == doc.object_id
end
end
|
module ApplicationHelper
FLASH_TYPES = {
alert: 'warning',
notice: 'info'
}.freeze
def flash_messages
flash.map do |type, message|
content_tag :div, sanitize(message), class: flash_type(type), role: 'alert'
end.join("\n").html_safe
end
def link_cache_key(link)
link_type = link.gist? ? 'gist' : 'simple'
"links/#{link.id}/#{link_type}-#{link.updated_at.to_f}"
end
def answer_cache_key(answer)
answer_type = answer.best? ? 'best' : 'simple'
"answers/#{answer.id}/#{answer_type}-#{answer.updated_at.to_f}"
end
private
def flash_type(type)
"alert alert-#{FLASH_TYPES[type.to_sym]}"
end
end
|
require 'rails_helper'
describe Voucher do
it "has a valid factory" do
expect(build(:voucher)).to be_valid
end
it "is valid with a code, valid_from, valid_through, amount, unit_type, max_amount" do
expect(build(:voucher)).to be_valid
end
it "is invalid without a code" do
voucher = build(:voucher, code: nil)
voucher.valid?
expect(voucher.errors[:code]).to include("can't be blank")
end
it "is invalid without a valid_from" do
voucher = build(:voucher, valid_from: nil)
voucher.valid?
expect(voucher.errors[:valid_from]).to include("can't be blank")
end
it "is invalid without a valid_through" do
voucher = build(:voucher, valid_through: nil)
voucher.valid?
expect(voucher.errors[:valid_through]).to include("can't be blank")
end
it "is invalid without an unit_type" do
voucher = build(:voucher, unit_type: nil)
voucher.valid?
expect(voucher.errors[:unit_type]).to include("can't be blank")
end
it "invalid with wrong unit_type" do
expect{ build(:voucher, unit_type: "dollar")}. to raise_error(ArgumentError)
end
it "is invalid with a duplicate code" do
voucher1 = create(:voucher, code: "GOJEKINAJA")
voucher2 = build(:voucher, code: "GOJEKINAJA")
voucher2.valid?
expect(voucher2.errors[:code]).to include("has already been taken")
end
it "is invalid if amount less than 0.01" do
voucher = build(:voucher, amount:0)
voucher.valid?
expect(voucher.errors[:amount]).to include("must be greater than or equal to 0.01")
end
it "is invalid if max_amount less than 0.01" do
voucher = build(:voucher, max_amount:0)
voucher.valid?
expect(voucher.errors[:max_amount]).to include("must be greater than or equal to 0.01")
end
describe "amount must be numeric" do
before :each do
@voucher1 = build(:voucher, amount: 15)
@voucher2 = build(:voucher, amount: "123a")
end
context "with numeric input amount" do
it "is valid amount numeric" do
expect(@voucher1.valid?).to eq(true)
end
end
context "with non numeric input amount" do
it "is invalid amount numeric" do
@voucher2.valid?
expect(@voucher2.errors[:amount]).to include("is not a number")
end
end
end
describe "max_amount must be numeric" do
before :each do
@voucher1 = build(:voucher, max_amount: 15)
@voucher2 = build(:voucher, max_amount: "123a")
end
context "with numeric input max_amount" do
it "is valid max_amount numeric" do
expect(@voucher1.valid?).to eq(true)
end
end
context "with non numeric input max_amount" do
it "is invalid max_amount numeric" do
@voucher2.valid?
expect(@voucher2.errors[:max_amount]).to include("is not a number")
end
end
end
it 'is code saved with upcase format' do
voucher = create(:voucher, code: 'downcase')
expect(voucher.code).to eq('DOWNCASE')
end
it 'with a invalid format date valid_from' do
voucher = build(:voucher, valid_from: 'badformat')
voucher.valid?
expect(voucher.errors[:valid_from]).to include("is invalid Date")
end
it 'with a invalid format date valid_through' do
voucher = build(:voucher, valid_through: 'badformat')
voucher.valid?
expect(voucher.errors[:valid_through]).to include("is invalid Date")
end
it 'invalid if valid_through < valid_from' do
voucher = build(:voucher, valid_through: '2017-11-6', valid_from: '2017-11-7')
voucher.valid?
expect(voucher.errors[:valid_through]).to include("must be greater than or equal to valid_from")
end
context "with unit value is rupiah" do
it "invalid with max_amount less than amount" do
voucher = build(:voucher, unit_type:0, amount:9000, max_amount: 8000)
voucher.valid?
expect(voucher.errors[:max_amount]).to include("must be greater or equal to amount")
end
end
it "is invalid with case insensetive duplicate cod" do
voucher1 = create(:voucher, code: "gojekinaja")
voucher2 = build(:voucher, code: "GOJEKINAJA")
voucher2.valid?
expect(voucher2.errors[:code]).to include("has already been taken")
end
it "cant be destroy while it hash order" do
voucher = create(:voucher)
order = create(:order, voucher: voucher)
voucher.orders << order
expect{voucher.destroy}.not_to change(Voucher, :count)
end
end
|
def sum_even_number_of_row(row_number)
rows = [] #step 1
start_integer = 2
(1..row_number).each do |current_row_number| #steps 2 & 3 used a range instead of a loop
rows << create_row(start_integer, current_row_number)
start_integer = rows.last.last + 2
end
# final_row_sum = 0
# rows.last.each{ |num| final_row_sum += num }
# final_row_sum
rows.last.sum
end
def create_row(start_integer, row_length)
row = [] #step 1
current_integer = start_integer #a more accurate name for our variable since start_integer isn't quite accurate after we increment it
loop do #steps 2-4
row << current_integer
current_integer += 2
break if row.length == row_length
end
row #step 5
end
#---------------------------------------------------------------
# ------- Test Cases for sum_even_number_of_row method: -------
# row number: 1 --> sum of integers in row: 2
# row number: 2 --> sum of integers in row: 10
# row number: 4 --> sum of integers in row: 68
p sum_even_number_of_row(1) == 2 #true
p sum_even_number_of_row(2) == 10 #true
p sum_even_number_of_row(4) == 68 #true
# ------ Algorithm for sum_even_number_of_rows method: ---------
# 1. Create an empty 'rows' array to contain all of the rows
# 2. Create the first row and add it to the 'rows' array (will happen within step 3's loop)
# 3. Repeat step 2 until all the necessary rows have been created in accordance with the input
# - All rows have been created when the length of the 'rows array is equal to the input integer
# 4. Sum the final row (Implementation level)
# 5. Return the sum of the final row
# -------------- Calculating the start integer: ---------------
# Rule: first integer of row == last integer of preceding row + 2
# Algorithm:
# - Get last row of the rows array
# - Get last integer of that row
# - add 2 to the integer
#--------------------------------------------------------------
# --------- Test Cases for helper method, create_row: ----------
# start: 2, length: 1 --> [2]
# start: 4, length: 2 --> [4, 6]
# start: 8, length: 3 --> [8, 10, 12]
p create_row(2, 1) == [2] #true
p create_row(4, 2) == [4, 6] #true
p create_row(8, 3) == [8, 10, 12] #true
# ------- Algorithm for helper method create_row: ------------
# 1. Create an empty 'row' array to contain the integers
# 2. Add the starting integers
# 3. Increment the starting integer by 2 to get the next integer in the sequence
# 4. Repeat (think loop) steps 2/3 until the array has reached the correct length
# 5. Return the 'row' array
#---------------- Step 4 - Loop Algorithm ---------------------
# Start the loop
# - Add the start integer to the row (step 2)
# - Increment the start integer by 2 (step 3)
# - Break out of the loop (if length of row equals row _length)
# --------------------------------------------------------------
|
# U2.W6: Create a Car Class from User Stories
# I worked on this challenge by myself.
# 2. Pseudocode
=begin
Methods:
initialize(model, color)
accelerate(acceleration)
decelerate(deceleration)
stop
turn left
turn right
previous action
drive(speed, distance)
Attributes:
distance travelled
speed
model
color
DEFINE car class with input model and color (Strings), pizzas (array of Strings)
SET model variable to model
SET color to color
SET pizza variable to pizzas
DEFINE check speed method to determine speed
RETURN speed variable (which should be defined somewhere)
DEFINE accelerate method with input acceleration
ADD acceleration to speed
DEFINE decelerate method with input deceleration
SUBTRACT deceleration from speed
DEFINE drive method with inputs speed and distance to drive
SET speed variable to speed
SET direction to direction
ADD distance to total distance variable
=end
# 3. Initial Solution
class Car
def initialize(color, model, pizzas = nil)
@color = color
@model = model
@speed = 0
@distance_traveled = 0
@pizza = pizzas
end
def drive(speed = @speed, distance)
@speed = speed
@distance_traveled += distance
puts "You drove your #{@model} #{distance} miles at #{@speed} mph"
end
def accelerate(acceleration)
@speed += acceleration
puts "You accelerated your #{@model} #{acceleration} mph to #{@speed} mph"
end
def decelerate(deceleration)
@speed -= deceleration
puts "You decelerated your #{@model} #{deceleration} mph to #{@speed} mph"
end
def stop
puts "You stopped!"
@speed = 0
end
def check_speed
puts "You are traveling at #{@speed} mph"
end
def turn_left
puts "You turned left!"
end
def turn_right
puts "You turned right!"
end
def total_distance
puts "You have traveled #{@distance_traveled} miles"
end
def deliver_pizza
puts "You delivered a #{@pizza.pop.type} pizza!"
end
def check_pizzas
return "No more pizzas to deliver! Success! Time to head home!" if @pizza == []
puts "You have the following pizzas to deliver:"
@pizza.each {|pizza| p pizza.type}
end
def remove_pizza
puts "A #{@pizza.pop.type} pizza has been removed from your #{@model}"
end
end
class Pizza
def initialize(type)
@type = type
end
def type
@type
end
end
# 4. Refactored Solution
# 1. DRIVER TESTS GO BELOW THIS LINE
mustang = Car.new('red', 'mustang')
mustang.drive(25, 0.25)
mustang.stop
mustang.turn_right
mustang.drive(35, 1.5)
mustang.check_speed
mustang.decelerate(20)
mustang.drive(0.25)
mustang.stop
mustang.turn_left
mustang.drive(35, 1.4)
mustang.stop
mustang.total_distance
# PIZZA DELIVERY
mushroom_pizza = Pizza.new('Mushroom')
pepperoni_pizza = Pizza.new('Pepperoni')
hawaiian_pizza = Pizza.new('Ham and Pineapple')
vegeterian_pizza = Pizza.new('Vegetarian')
pizzas = [mushroom_pizza, pepperoni_pizza, hawaiian_pizza, vegeterian_pizza]
delivery_car = Car.new('grey', 'Delorean', pizzas)
delivery_car.drive(25, 1)
p "You've arrived at work in Papa Johns in Moscow!"
delivery_car.check_pizzas
p "First pizza to be delivered is near Paveletskaya Rail Station 10 miles away!"
p "You have 20 minutes to get there!"
delivery_car.drive(30, 10)
delivery_car.stop
delivery_car.deliver_pizza
p "Second pizza to be delivered is near Gorky Park 5 miles away!"
p "You have 5 minutes to get there!!"
delivery_car.drive(60, 3)
p "A car from the city traffic police is following you!"
delivery_car.decelerate(30)
p "The police car turned left and is no longer behind you!"
delivery_car.accelerate(70)
delivery_car.turn_right
delivery_car.stop
delivery_car.deliver_pizza
p "A group of gopniki are eating sunflower seeds in the stairwell!"
p "They steal two of your pizzas!"
delivery_car.remove_pizza
delivery_car.remove_pizza
p delivery_car.check_pizzas
# 5. Reflection
=begin
I really enjoyed working through this exercise. I found that the method of writing out
the methods and attributes first then taking a look at the driver code before writing the
pseudocode really allowed me to write the code very quickly.
There were a few things that I noticed while working through this. First I saw an error
when trying to write the code "return puts 'string' if @foo = bar". Ruby actually doesn't
catch the error and allows me to write an assignment in an if statement. Thus it was
setting @foo to bar and then returning an error when subsequent methods used @foo and didn't
get what they were expecting. I am not really sure why it wouldn't catch that but I should look
further into this.
I also made the choice to add a type method to the pizza class instead of using the attr_reader
to print the type which I had done in previous exercises. I think that this makes for cleaner code.
=end |
class Zoo
@@all = []
attr_reader :name, :location
def initialize(name, location)
@name = name
@location = location
@@all << self
end
def self.all
@@all
end
def animals
Animal.all.select{ |animal|
self == animal.zoo
}
end
def animal_species
animals.map { |animal|
animal.species
}.uniq
end
def find_by_species(species)
animals.select {|animal|
animal.species == species
}
end
def animal_nicknames
animals.map{ |name|
name.nickname
}
end
def self.find_by_location(location)
@@all.select{ |zoo|
zoo.location == location
}
end
end
|
require 'test_helper'
class CostDetailsControllerTest < ActionDispatch::IntegrationTest
setup do
@cost_detail = cost_details(:one)
end
test "should get index" do
get cost_details_url
assert_response :success
end
test "should get new" do
get new_cost_detail_url
assert_response :success
end
test "should create cost_detail" do
assert_difference('CostDetail.count') do
post cost_details_url, params: { cost_detail: { cost: @cost_detail.cost, cost_type: @cost_detail.cost_type, maintenance_history_id: @cost_detail.maintenance_history_id, provider: @cost_detail.provider } }
end
assert_redirected_to cost_detail_url(CostDetail.last)
end
test "should show cost_detail" do
get cost_detail_url(@cost_detail)
assert_response :success
end
test "should get edit" do
get edit_cost_detail_url(@cost_detail)
assert_response :success
end
test "should update cost_detail" do
patch cost_detail_url(@cost_detail), params: { cost_detail: { cost: @cost_detail.cost, cost_type: @cost_detail.cost_type, maintenance_history_id: @cost_detail.maintenance_history_id, provider: @cost_detail.provider } }
assert_redirected_to cost_detail_url(@cost_detail)
end
test "should destroy cost_detail" do
assert_difference('CostDetail.count', -1) do
delete cost_detail_url(@cost_detail)
end
assert_redirected_to cost_details_url
end
end
|
class AddAttachmentsToGallery < ActiveRecord::Migration[5.0]
def change
add_column :galleries, :attachments, :string, array: true, default: []
end
end
|
class AddAndRenameColumnToEntities < ActiveRecord::Migration
def change
rename_column :entities, :surname, :paternal_surname
add_column :entities, :maternal_surname, :string
end
end
|
# Modelo Episodio
# Tabla episodios
# Campos id:integer
# medico_id:integer
# paciente_id:integer
# fecha:date
# hora:time
# historia_enfermedad_actual:text
# aparatos_sistemas:string
# fuma:boolean
# fuma_frecuencia:string
# toma:boolean
# toma_frecuencia:string
# drogas:boolean
# drogas_frecuencia:string
# drogas_lista:text
# habitos:string
# notas_subjetivo:text
# exploracion_fisica:string
# peso:float
# talla:float
# presion:string
# frecuencia_cardiaca:string
# frecuencia_respiratoria:string
# notas_objetivo:text
# notas_evaluacion:text
# estudio_laboratorio:text
# estudio_gabinete:text
# procedimientos:text
# notas_plan:text
# medico_interconsulta_id:integer
# diagnostico:text
# alergias:text
# medicamentos:text
# tipo_consulta:integer
# created_at:datetime
# updated_at:datetime
class Episodio < ActiveRecord::Base
TIPOS_CONSULTA = [PRIMERA_CONSULTA = 0, SUBSECUENTE = 1]
STATUS = [AGENDADO = 0, VALIDADO = 1, EN_CONSULTA = 2, ALTA_MEDICA = 3]
belongs_to :medico, inverse_of: :episodios
belongs_to :medico_interconsulta, class_name: 'Medico',
inverse_of: :episodios_interconsulta
belongs_to :paciente, inverse_of: :episodios
has_many :medicamentos_episodio, inverse_of: :episodio, dependent: :destroy
has_many :motivos_consulta_episodio, inverse_of: :episodio,
dependent: :destroy
has_many :diagnosticos_episodio, inverse_of: :episodio, dependent: :destroy
has_many :padecimientos_episodio, inverse_of: :padecimiento,
dependent: :destroy
has_many :alergenos_episodio, inverse_of: :episodio, dependent: :destroy
validates :medico, presence: true
validates :paciente, presence: true, uniqueness: { scope: [:fecha, :hora] }
validates :fecha, presence: true
validates :hora, presence: true, uniqueness: { scope: [:fecha, :medico] }
validates :tipo_consulta, presence: true, inclusion: { in: TIPOS_CONSULTA }
validates :status, presence: true, inclusion: { in: STATUS }
validates :fuma_frecuencia, presence: { if: :fuma }
validates :drogas_frecuencia, presence: { if: :drogas }
validates :drogas_lista, presence: { if: :drogas }
end
|
class AddColumnUserIdToRepeatExceptions < ActiveRecord::Migration[4.2]
def change
add_column :repeat_exceptions, :user_id, :integer
add_index :repeat_exceptions, :user_id
end
end
|
class Event < ApplicationRecord
belongs_to :user
# belongs_to :place
belongs_to :sport
has_many :participations, dependent: :destroy
has_many :messages
validates :name, presence: true
validates :name, uniqueness: true
validates :required_level, presence: true
#validates :status, presence: true
validates :required_material, presence: true
validates :sport, presence: true
validates :date, presence: true
validates :address, presence: true
validates :number_of_players, presence: true
geocoded_by :address
after_validation :geocode, if: :address_changed?
end
|
class AddEndsOnToExchangeRates < ActiveRecord::Migration
def change
add_column :exchange_rates, :ends_on, :date, null: false
end
end
|
class ResumePresenter
def initialize view, &block
@view = view
yield(self)
end
def resume organization, type
text = Resume.translate organization, type
return if text.blank?
h.content_tag(:p, class: type) {
h.content_tag(:span, I18n.t("documents.resume.#{type}")) + text
}
end
private
def h
@view
end
end
|
Rails.application.routes.draw do
root 'dashboard#index'
resources :users
resources :rooms
resources :bookings
end
|
require 'rails_helper'
require 'support/factory_girl'
describe "Artists new interface", :type => :feature do
describe "page" do
before do
visit new_artist_path
end
it { expect(page).to have_title("Add artist") }
# it { expect(page).to have_content("Add artist") }
end
describe "with valid information" do
before do
visit new_artist_path
fill_in "Name", with: "Masatoshi Nishiguchi"
fill_in "Nationality", with: "Japan"
fill_in "Photo url", with: "http://mnishiguchi.com/images/masatoshi_chinatown_300.png"
click_button "Add artist"
end
it { expect(page).to have_content(/created/i) } # "Artist created"
# it { expect(page).to have_css("single_artist") }
end
end
|
module AadhaarAuth
class Encrypter
ENC_ALGO = 'AES-256-ECB'
def session_key
@session_key ||= begin
aes = OpenSSL::Cipher.new(ENC_ALGO)
aes.encrypt
aes.random_key
end
end
def encrypted_session_key
@encrypted_session_key ||= begin
public_key = public_cert.public_key
Base64.encode64(public_key.public_encrypt(session_key))
end
end
def encrypt_using_session_key(data)
aes = OpenSSL::Cipher.new(ENC_ALGO)
aes.encrypt
aes.key = session_key
(aes.update(data) + aes.final)
end
def calculate_hmac(data)
Base64.encode64(encrypt_using_session_key(Digest::SHA256.digest(data)))
end
def public_cert
self.class.public_cert
end
class << self
def public_cert
@public_cert ||= OpenSSL::X509::Certificate.new(File.read(Config.public_certificate_path))
end
end
end
end |
class Haiku
include ActiveModel::Validations
include HaikuChecker
attr_accessor :line1, :line2, :line3
attr_accessor :line1_valid, :line2_valid, :line3_valid, :valid, :checked
def initialize
@line1 = "An old silent pond,"
@line2 = "A frog jumps into the pond,"
@line3 = "Splash! Silence again."
@checked = false;
end
def check
@checked = true;
@line1_valid = HaikuChecker.check(@line1, 5)
@line2_valid = HaikuChecker.check(@line2, 7)
@line3_valid = HaikuChecker.check(@line3, 5)
@valid = @line1_valid && @line2_valid && @line3_valid
end
end
|
require 'spec_helper'
feature 'Removing Member from Project', js: true do
scenario 'persisted user' do
project = factory!(:project)
member = factory!(:user)
surety = factory!(:surety, project: project)
factory!(:surety_member, user: member, surety: surety)
surety.generate!
surety.activate!
sign_in project.user
visit project_path(project)
find(:role, 'remove-member').click
expect(page).to_not have_content(member.full_name)
end
scenario 'invited user' do
project = factory!(:project)
surety = factory!(:surety, project: project)
member = factory!(:new_surety_member, surety: surety)
surety.generate!
surety.activate!
sign_in project.user
visit project_path(project)
find(:role, 'remove-member').click
expect(page).to_not have_content(member.full_name)
end
end
|
module Worker
class DepositCoinAddress
def process(payload, metadata, delivery_info)
payload.symbolize_keys!
payment_address = PaymentAddress.find payload[:payment_address_id]
return if payment_address.address.present?
currency = payload[:currency]
if currency == 'tlcp'
c = Currency.find_by_code(currency)
address = CoinRPC[currency].personal_newAccount(c.password)
else
# address = CoinRPC[currency].getnewaddress("payment")
# address = get_callback_address('ltct')
address = get_callback_address(currency)
end
if payment_address.update address: address
::Pusher["private-#{payment_address.account.member.sn}"].trigger_async('deposit_address', { type: 'create', attributes: payment_address.as_json})
end
end
def get_callback_address(currency)
args = { currency: currency }
r = Coinpayments.api_call(args)
# Rails.logger.info "#{r}"
return r.address
end
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
@airline = Airline.create!(name: "Delta")
@flight1 = @airline.flights.create!(number: "1727", date: "08-03-20", time: "3:30pm MST", departure_city: "Denver", arrival_city: "Reno")
@flight2 = @airline.flights.create!(number: "7777", date: "08-03-20", time: "8:30pm MST", departure_city: "Reno", arrival_city: "Seattle")
@flight3 = @airline.flights.create!(number: "1776", date: "08-04-20", time: "8:30am PST", departure_city: "Seattle", arrival_city: "Houston")
@joe = Passenger.create!(name: "Joe", age: "7")
@bob = Passenger.create!(name: "Bob", age: "77")
FlightPassenger.create!(flight: @flight1, passenger: @joe)
FlightPassenger.create!(flight: @flight1, passenger: @bob)
FlightPassenger.create!(flight: @flight2, passenger: @joe)
FlightPassenger.create!(flight: @flight2, passenger: @bob)
|
class Reports::FastRegionTreeComponent < ViewComponent::Base
attr_reader :region_tree, :parent, :children
def initialize(region_tree:, parent:, children:)
@region_tree = region_tree
@children = children
@parent = parent
end
OFFSET = 2
# Note that we short circuit facility access checks because they are handled in the controller, as they are the
# leaf nodes that are returned via our accessible region view_reports finder. This avoids the many extra authz checks for
# index view, which could be in the thousands for users with a lot of access.
def accessible_region?(region, action)
case region.region_type
when "facility"
true
else
helpers.accessible_region?(region, action)
end
end
def depth(region)
depth = Region::REGION_TYPES.index(region.region_type) - OFFSET
depth += 1 if region.child_region_type.nil?
depth
end
def render?
children&.any?
end
end
|
NET = "192.168.90."
Vagrant.configure("2") do |config|
vm_no = 5
(1..vm_no).each do |machine_id|
config.vm.define "hadoop0#{machine_id}" do |machine|
machine.vm.hostname = "hadoop0#{machine_id}"
machine.vm.box = "centos/7"
machine.vm.network "forwarded_port", guest: 22, host: "269#{machine_id}", id: "ssh"
machine.ssh.port = "269#{machine_id}"
machine.vm.network "private_network", ip: NET + "5#{machine_id}"
machine.ssh.shell = "bash -c 'BASHENV=/etc/profile exec bash'"
machine.vm.provision "shell" do |sh|
sh.inline = "export CENTOS_FRONTEND=noninteractive"
sh.inline = "touch /swpfile; chmod 0600 /swpfile; dd if=/dev/zero of=/swpfile bs=8M count=1024; mkswap /swpfile; swapon /swpfile; swapon -s"
end
machine.vm.provider "virtualbox" do |vb|
vb.memory = 2048
vb.cpus = 2
vb.customize ["modifyvm", :id, "--cpuexecutioncap", "50"]
end
if machine_id == vm_no
machine.vm.provision "ansible" do |ansible|
ansible.limit = "all"
ansible.verbose = "-v"
ansible.become = true
ansible.raw_arguments = ['-v']
ansible.playbook = "site.yml"
ansible.tags = ["hadoop"]
ansible.inventory_path = "inventory"
ansible.extra_vars = {
ansible_ssh_users: 'vagrant'
}
ansible.groups = {
"had" => ["hadoop01", "hadoop02"],
"worker" => ["hadoop03", "hadoop04", "hadoop05"]
}
end
end
end
end
end
|
require "pry"
module Api::V1
class UsersController < ApplicationController
before_action :set_user, only: [:show, :update, :destroy, :user_matches]
skip_before_action :authorized, only: [:create]
# GET /users
def index
@users = User.all
render json: @users
end
def user_matches
render json: @user.matches.uniq{|m| m.id}
end
def profile
render json: { user: @user }, status: :accepted
end
# GET /user/1
def show
render json: @user
end
def find_user
@user = User.find_by(username: params[:username])
render json: @user
end
def search_users
@users = User.select { |user| user.username.include?(params[:username]) }
render json: @users
end
def user_match_holes
holes = Hole.find_by(match_id: params[:match_id])
render json: @user.holes
end
def find_multiple_users_by_name
players = params[:playerNameList].split(',')
playersObject = []
players.each do | player |
playersObject.push(User.find_by(username: player))
end
render json: playersObject
end
def find_multiple_users_by_id
players = params[:playerIDList].split(',')
playersObject = []
players.each do | player |
playersObject.push(User.find(player))
end
render json: playersObject
end
# POST /user
def create
@user = User.new(user_params)
if @user.valid?
@user.save
@token = encode_token(user_id: @user.id)
render json: { user: @user, jwt: @token }, status: :created
else
render json: @user.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /users/1
def update
if @user.update(user_params)
render json: @user
else
render json: @user.errors, status: :unprocessable_entity
end
end
# DELETE /users/1
def destroy
@user.destroy
if @user.destroy
head :no_content, status: :ok
else
render json: @user.errors, status: :unprocessable_entity
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end
# Only allow a trusted parameter "user" through.
def user_params
params.require(:user).permit(:username, :email, :password)
end
end
end
|
module Rpodder
class Runner < Base
def initialize(*args)
load_config!
load_database!
parse_options
end
def parse_options
trap_interrupt
Rpodder::CLI.start
remove_unused!
clean_history
end
def trap_interrupt
Signal.trap('INT') do
error "\n\nCaught Ctrl-C, exiting!"
exit 1
end
end
def clean_history
podcasts = Podcast.all
limit = @conf['max-items'] * 100
offset = @conf['max-items']
podcasts.each { |pcast| pcast.episodes.all(:limit => limit, :offset => offset).destroy }
end
def remove_unused!
podcasts_to_remove.each do |pcast|
say "Removing unused #{pcast}"
Podcast.all(:rssurl => pcast).destroy
end
end
protected
def podcasts_to_remove
podcasts - urls
end
end
end
|
class CreateServiceLinks < ActiveRecord::Migration
def change
create_table :service_links do |t|
t.references :linked_to_service, index: true
t.references :linked_from_service, index: true
t.string :alias
t.timestamps
end
add_index :service_links, [:linked_from_service_id, :linked_to_service_id], unique: true, name: 'index_service_link_keys'
end
end
|
class OrderController < ApplicationController
before_filter :find_order, only: [ :show, :edit, :update, :destroy ]
def index
@order = Order.all
end
def show
if @order.client_id.nil?
@msg = "No client found for this order"
else
@clie = @order.client
@msg= @clie.name
end
end
def new
@order = Order.new
end
def edit
end
def create
@order = Order.create(params[:order].merge(:startorder => Date.today))
if @order.errors.empty?
redirect_to order_path(@order)
else
render "new"
end
end
def update
@order.update_attributes(params[:order])
if @order.errors.empty?
redirect_to order_path(@order)
else
render "edit"
end
end
def destroy
@order.destroy
redirect_to action: "index"
end
private
def find_order
@order = Order.where(id: params[:id]).first
end
end
|
# There are several types of bodies we're concerned about in our solar system:
# planets, stars (like our sun), and moons. We'll ignore asteroids and smaller
# planetoids (sorry Pluto).
#
# Each of our body types needs a class: Planet, Star, and Moon.
# All of these bodies have some similarities: they all have a name and a mass.
# So, let's also make them inherit from Body. They do have some unique qualities though.
#
# Moons:
#
# Have a month, which is the number of days it takes for the moon to orbit its
# planet. Again, this can either be Earth days or the planet's days, your choice.
# Have a planet that they orbit. We want to store the whole Planet object here.
require_relative 'body'
class Moon < Body
def initialize(name, mass, moon_orbit_day, moon_orbit_planet)
super(name, mass)
@moon_orbit_day = moon_orbit_day
@moon_orbit_planet = moon_orbit_planet
end
def moon_orbit_day
@moon_orbit_day
end
def moon_orbit_planet
@moon_orbit_planet
end
end
|
require 'spec_helper'
require_relative '../../../lib/scrapers/berlinale_programme'
RSpec.describe Scrapers::BerlinaleProgramme do
subject { described_class.new(page) }
let(:page) { 20 }
describe '#data' do
it 'returns some data' do
VCR.use_cassette("berlinale_page_#{page}") do
expect(subject.data).to be_a String
expect(subject.send(:success?)).to be true
end
end
end
end
|
class AddCreatedByIdToEuDecisions < ActiveRecord::Migration
def change
add_column :eu_decisions, :created_by_id, :integer
end
end
|
FactoryGirl.define do
factory :treatment_type do
sequence(:name) { |n| "Treatment type #{n}" }
treatment_types_group
end
end
|
require 'spec_helper'
describe "Proxy + WebDriver" do
let(:driver) { Selenium::WebDriver.for :firefox, :profile => profile }
let(:proxy) { new_proxy }
let(:wait) { Selenium::WebDriver::Wait.new(:timeout => 10) }
let(:profile) {
pr = Selenium::WebDriver::Firefox::Profile.new
pr.proxy = proxy.selenium_proxy
pr
}
after {
driver.quit
proxy.close
}
describe 'request interceptor' do
it "modifies request" do
proxy.new_har("1", :capture_headers => true)
proxy.request_interceptor = 'request.getMethod().setHeader("foo", "bar");'
driver.get url_for("1.html")
wait.until { driver.title == '1' }
entry = proxy.har.entries.first
header = entry.request.headers.find { |h| h['name'] == "foo" }
header['value'].should == "bar"
end
end
it "should fetch a HAR" do
proxy.new_har("1")
driver.get url_for("1.html")
wait.until { driver.title == '1' }
proxy.new_page "2"
driver.get url_for("2.html")
wait.until { driver.title == '2' }
har = proxy.har
har.should be_kind_of(HAR::Archive)
har.pages.size.should == 2
end
it "should fetch a HAR and capture headers" do
proxy.new_har("2", :capture_headers => true)
driver.get url_for("2.html")
wait.until { driver.title == '2' }
entry = proxy.har.entries.first
entry.should_not be_nil
entry.request.headers.should_not be_empty
end
it "should fetch a HAR and capture content" do
proxy.new_har("2", :capture_content => true)
driver.get url_for("2.html")
wait.until { driver.title == '2' }
entry = proxy.har.entries.first
entry.should_not be_nil
entry.response.content.size.should be > 0
entry.response.content.text.should == File.read("spec/fixtures/2.html")
end
it "should fetch a HAR and capture binary content as Base64 encoded string" do
proxy.new_har("binary", :capture_binary_content => true)
driver.get url_for("empty.gif")
entry = proxy.har.entries.first
entry.should_not be_nil
entry.response.content.size.should be > 0
require 'base64'
expected_content = Base64.encode64(File.read("spec/fixtures/empty.gif")).strip
entry.response.content.text.should == expected_content
end
describe 'whitelist' do
it "allows access to urls in whitelist" do
dest = url_for('1.html')
proxy.whitelist(Regexp.quote(dest), 404)
driver.get dest
wait.until { driver.title == '1' }
end
it "disallows access to urls outside whitelist" do
proxy.new_har('whitelist')
proxy.whitelist('foo\.bar\.com', 404)
driver.get url_for('2.html')
proxy.har.entries.first.response.status.should == 404
end
it "can be cleared" do
proxy.new_har('whitelist')
proxy.whitelist('foo\.bar\.com', 404)
proxy.clear_whitelist
driver.get url_for('2.html')
proxy.har.entries.first.response.status.should_not == 404
end
end
describe 'blacklist' do
it "disallows access to urls in blacklist" do
proxy.new_har('blacklist')
dest = url_for('1.html')
proxy.blacklist(Regexp.quote(dest), 404)
driver.get dest
entry = proxy.har.entries.find { |e| e.request.url == dest }
entry.should_not be_nil
entry.response.status.should == 404
end
it "allows access to urls outside blacklist" do
proxy.blacklist('foo\.bar\.com', 404)
driver.get url_for('2.html')
wait.until { driver.title == '2' }
end
it "can be cleared" do
proxy.new_har('blacklist')
dest = url_for('1.html')
proxy.blacklist(Regexp.quote(dest), 404)
proxy.clear_blacklist
driver.get dest
entry = proxy.har.entries.find { |e| e.request.url == dest }
entry.should_not be_nil
entry.response.status.should_not == 404
end
end
describe 'rewrite rules' do
let(:uri) { URI.parse url_for('1.html') }
before do
proxy.rewrite(%r{1\.html}, '2.html')
end
it 'fetches the rewritten url' do
driver.get uri
wait.until { driver.title == '2' }
end
it 'can be cleared' do
proxy.clear_rewrites
driver.get uri
wait.until { driver.title == '1' }
end
end
it 'should set timeouts' do
proxy.timeouts(read: 0.001)
driver.get url_for('slow')
wait.until { driver.title == 'Problem loading page' } # This title appears in Firefox
end
it "should set headers" do
proxy.headers('Content-Type' => "text/html")
end
it "should set limits" do
proxy.limit(:downstream_kbps => 100, :upstream_kbps => 100, :latency => 2)
end
it 'should remap given DNS hosts' do
uri = URI.parse url_for('1.html')
host = 'plus.google.com'
proxy.remap_dns_hosts(host => uri.host)
uri.host = host
driver.get uri
wait.until { driver.title == '1' }
end
end
|
module Perpetuity
class IdentityMap
def initialize
@map = Hash.new { |hash, key| hash[key] = {} }
end
def [] klass, id
@map[klass][id]
end
def << object
klass = object.class
id = object.instance_variable_get(:@id)
@map[klass][id] = object
end
def ids_for klass
@map[klass].keys
end
end
end
|
class ImportTrail < ApplicationRecord
belongs_to :import
scope :with_errors, -> { where.not(error_msg: nil) }
scope :without_errors, -> { where(error_msg: nil) }
scope :last_day, -> { where('created_at > ?', 1.day.ago) }
def duration_time
time_span = (finished_at || Time.current) - created_at
Time.at(time_span).utc.strftime('%H:%M:%S')
end
end
|
class Inquiry
include ActiveModel::Model
attr_accessor :name, :tel, :email, :inquiry_details
validates :name, presence: true, length: { maximum: 20 }
validates :tel, presence: true, numericality: true, length: { maximum: 15 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX }
def valid?
valid_inquiry_details = @inquiry_details.map { |v| v.valid? }.all?
super && valid_inquiry_details
end
def save
end
def inquiry_details_attributes=(attributes)
@inquiry_details = attributes.map { |_k, v| InquiryDetail.new(v) }
end
end
|
class CreateListedCitizens < ActiveRecord::Migration
def change
create_table :listed_citizens do |t|
t.references :citizen
t.references :list
t.timestamps
end
add_index :listed_citizens, [:citizen_id, :list_id]
add_index :listed_citizens, [:list_id, :citizen_id]
end
end
|
# == Schema Information
#
# Table name: logs
#
# id :uuid not null, primary key
# guest_id :integer
# access_token :string
# created_at :datetime not null
#
class Log < ApplicationRecord
belongs_to :guest
validates :guest, presence: true
validates :access_token, presence: true
scope :created_after, -> (time) { where("created_at > ?", time) }
scope :from_today, -> { where("created_at > ?", DateTime.now.beginning_of_day) }
scope :from_and_until_selected_day, -> (datetime) { where("created_at > ? AND created_at < ? ", datetime.beginning_of_day, datetime.end_of_day) }
scope :not_created_by, -> (access_token) { where("access_token != ? OR access_token IS NULL", access_token) }
end
|
require "spec_helper"
describe Lita::Handlers::Redmine, lita_handler: true do
before do
Lita.configure do |config|
config.handlers.redmine.url = "https://redmine.example.com"
config.handlers.redmine.type = :chiliproject
config.handlers.redmine.apikey = "0000000000000000000000000000000000000000"
end
end
it { is_expected.to route("get me redmine 12345, please").to(:issue) }
it { is_expected.not_to route("redmine foo").to(:issue) }
describe "#issue" do
let(:response) do
response = double("Faraday::Response")
allow(response).to receive(:status).and_return(200)
response
end
describe "params" do
it "replies with error if URL is not defined" do
Lita.configure do |config|
config.handlers.redmine.url = nil
end
send_command("redmine 42")
expect(replies.last).to eq("Error: Redmine URL must be defined ('config.handlers.redmine.url')")
end
it "replies with error if API key is not defined" do
Lita.configure do |config|
config.handlers.redmine.apikey = nil
end
send_command("redmine 42")
expect(replies.last).to eq("Error: Redmine API key must be defined ('config.handlers.redmine.apikey')")
end
it "replies with error if Type is not defined" do
Lita.configure do |config|
config.handlers.redmine.type = nil
end
send_command("redmine 42")
expect(replies.last).to eq("Error: Redmine type must be :redmine (default) or :chiliproject ('config.handlers.redmine.type')")
end
end
before do
allow_any_instance_of(Faraday::Connection).to receive(:get).and_return(response)
end
it "replies with the title and URL for the issue" do
allow(response).to receive(:body).and_return(<<-JSON.chomp
{
"issue": {
"author": {
"name": "The Greybeards",
"id": 70
},
"subject": "Destroy Alduin",
"priority": {
"name": "High",
"id": 4
},
"updated_on": "2013-10-31T17:07:20+01:00",
"done_ratio": 0,
"start_date": "2012-11-22",
"status": {
"name": "Assigned",
"id": 2
},
"project": {
"name": "Skyrim",
"id": 1
},
"description": "",
"assigned_to": {
"name": "Dovahkin",
"id": 99
},
"tracker": {
"name": "Bug",
"id": 2
},
"created_on": "2012-11-22T14:52:33+01:00",
"id": 42
}
}
JSON
)
send_command("redmine 42")
expect(replies.last).to eq("https://redmine.example.com/issues/42 : Destroy Alduin")
end
it "replies that the issue doesn't exist" do
allow(response).to receive(:status).and_return(404)
send_command("redmine 42")
expect(replies.last).to eq("Issue #42 does not exist")
end
it "replies with an excception message" do
allow(response).to receive(:status).and_return(500)
send_command("redmine 42")
expect(replies.last).to match(/^Error: /)
end
end
end
|
require 'spec_helper'
describe Survey do
it 'should create a survey with a correct ID' do
VCR.use_cassette 'models/survey/survey_success' do
FactoryGirl.create(:survey).should be_valid
end
end
it 'should not create a survey with a incorrect ID' do
VCR.use_cassette 'models/survey/survey_error' do
FactoryGirl.build(:survey, sg_id: 1111).should_not be_valid
end
end
it 'should parse the csv when the parseCSV method is called' do
VCR.use_cassette 'models/survey/survey_error' do
q_json_string = '['
q_json_string += '{"id":1,"_subtype":"checkbox","title":{"English":"Question - Checkbox"},"options":['
q_json_string += '{"id":10010,"value":"One"},{"id":10011,"value":"Two"},{"id":10012,"value":"Three"}'
q_json_string += ']},'
q_json_string += '{"id":2,"_subtype":"textbox","title":{"English":"Question - String"}}'
q_json_string += ']'
r_json_string = '['
r_json_string += '{"id":"1","[question(1), option(10013)]":"One","[question(1), option(10014)]":"Two", "[question(2)]":"Test one"},'
r_json_string += '{"id":"2","[question(1), option(10013)]":"One","[question(2)]":"Test two"}'
r_json_string += ']'
survey = FactoryGirl.create(:survey)
survey.update_attributes(questions_json: q_json_string, responses_json: r_json_string)
survey.parseCSV
# For some reason the regex just will not match, hence checking for each row text.
survey.csv.should include('question_checkbox,question_string')
survey.csv.should include('One Two ,Test one')
survey.csv.should include('One ,Test two')
end
end
end
|
class Author < ApplicationRecord
has_and_belongs_to_many :books, autosave: true
accepts_nested_attributes_for :books
validates :first_name, :last_name, presence: true
validates_format_of :group, with: %r{([A-Z]+)-(\d+)/(\d+)}i
def as_json(_options = {})
super(include: { books: { except: [] } })
end
end
|
class ArticlesController < ApplicationController
respond_to :html
skip_before_action :authenticate_user!, only: [:show, :index]
before_action :set_article, only: [:show, :edit, :update, :destroy]
impressionist actions: [:show]
def index
@articles = Article.all
respond_with(@articles)
end
def show
@clicks = @article.track_clicks_per_article
impressionist @article, message: "A User has viewed your article"
@url = request.fullpath.to_s
@ip = request.remote_ip
@country = request.location.country
@city = request.location.city
if user_signed_in? && (current_user.id != @article.user_id)
@clicks = @article.track_clicks_per_article
Click.record @url, @ip, @country, @city, @article.id, current_user.id.to_s
elsif !user_signed_in?
Click.record @url, @ip, @country, @city, @article.id, "anonymous"
end
respond_with(@article)
end
def new
@article = Article.new
respond_with(@article)
end
def edit
end
def create
@article = Article.new(article_params)
@article.save
respond_with(@article)
end
def update
@article.update(article_params)
respond_with(@article)
end
def destroy
@article.destroy
respond_with(@article)
end
private
def set_article
@article ||= Article.find params[:id]
end
def article_params
params.require(:article).permit :title, :body, :_slugs, :user_id
end
end
|
require "test_helper"
class AdminUserTest < ActiveSupport::TestCase
def test_should_be_valid
assert FactoryBot.create(:admin_user).valid?
end
def test_send_reset_password_email
admin_user = FactoryBot.create(:admin_user)
old_perishable_token = admin_user.perishable_token
mailer = mock
mailer.expects(:deliver)
Notifier.expects(:admin_user_reset_password).with(admin_user).returns(mailer)
admin_user.send_reset_password_email
assert_not_equal(old_perishable_token, admin_user.perishable_token)
end
def test_scope_order_by_recent
admin_user_1 = FactoryBot.create(:admin_user, uuid: "1001", created_at: "2021-04-19")
admin_user_2 = FactoryBot.create(:admin_user, uuid: "1002", created_at: "2021-04-20")
admin_user_3 = FactoryBot.create(:admin_user, uuid: "1003", created_at: "2021-04-21")
assert_primary_keys([admin_user_3, admin_user_2, admin_user_1], AdminUser.order_by_recent)
end
end
|
class HomeController < ApplicationController
def index
if session.has_key? :url_after_oauth
redirect_to session[:url_after_oauth]
end
end
end
|
class CreateUtilityCharges < ActiveRecord::Migration
def change
create_table :utility_charges do |t|
t.string :utility_name
t.decimal :utility_charge, precision: 6, scale: 2
t.string :utility_charge_date
t.references :property, index: true
t.timestamps
end
end
end
|
class NestCommand
def self.command(settings)
new.command(settings)
end
def command(settings)
return unless Rails.env.production? || Rails.env.test?
ActionCable.server.broadcast(:nest_channel, { loading: true })
get_devices if DataStorage[:nest_devices].blank?
settings = settings.to_s.squish.downcase
device_name = "Upstairs" if settings.match?(/(up|rooms)/i)
device_name ||= "Entryway"
device_data = (DataStorage[:nest_devices] || {})[device_name.to_sym]
device = GoogleNestDevice.new(nil, device_data)
@mode = nil
@temp = nil
@mode = :heat if settings.match?(/\b(heat)\b/i)
@mode = :cool if settings.match?(/\b(cool)\b/i)
device.mode = @mode if @mode
@temp = settings[/\b\d+\b/].to_i if settings.match?(/\b\d+\b/)
device.temp = settings[/\b\d+\b/].to_i if @temp
get_devices
if @mode.present? && @temp.present?
"Set house #{device_name.downcase} #{@mode == :cool ? "AC" : "heat"} to #{@temp}°."
elsif @mode.present? && @temp.blank?
"Set house #{device_name.downcase} to #{@mode}."
elsif @mode.blank? && @temp.present?
"Set house #{device_name.downcase} to #{@temp}°."
end
rescue StandardError => e
ActionCable.server.broadcast(:nest_channel, { failed: true })
if e.message == "400 Bad Request"
RefreshNestMessageWorker.perform_async
else
backtrace = e.backtrace&.map {|l|l.include?('app') ? l.gsub("`", "'") : nil}.compact.join("\n")
SlackNotifier.notify("Failed to set Nest: #{e.inspect}\n#{backtrace}")
end
end
def get_devices
subscription ||= GoogleNestControl.new
ActionCable.server.broadcast(:nest_channel, { devices: subscription.devices.map(&:to_json) })
end
end
|
class Song < ApplicationRecord
belongs_to :user
has_many :counts,dependent: :destroy
has_many :users, through: :counts,dependent: :destroy
validates :artist, presence:true
validates :title, presence:true
validates :artist, length: { minimum: 2 }
validates :title, length: { minimum: 2 }
end
|
require 'rails_helper'
RSpec.describe 'Chat stories' do
before do
allow(REDIS).to receive(:incr).with('user_count').and_return(1, 2, 3)
end
it "displays chat app" do
visit root_url
expect(page).to have_selector('h1', text: 'Public chat')
within('#message-input') do
expect(page).to have_selector('.username', text: 'User1')
expect(page).to have_selector('textarea')
expect(page).to have_selector('button')
end
end
it "assigns username for each session" do
visit root_url
expect(page).to have_selector('.username', text: 'User1')
using_session('other session') do
visit root_url
expect(page).to have_selector('.username', text: 'User2')
end
using_session('yet another session') do
visit root_url
expect(page).to have_selector('.username', text: 'User3')
end
end
it "does not assign user for same session" do
visit root_url
visit root_url
expect(page).to have_selector('.username', text: 'User1')
end
describe "send message to chatroom" do
let(:message_text) { 'hello' }
subject do
visit root_url
fill_in('messageText', with: message_text)
click_button 'Send'
end
it "renders sent message" do
subject
expect(page).to have_selector('#message-list li', text: "User1: #{message_text}")
end
it "renders message sent by other" do
visit root_url
using_session('other') do
visit root_url
subject
end
expect(page).to have_selector('#message-list li', text: "User2: #{message_text}")
end
it "clears message input text" do
subject
expect(find_field('messageText').value).to be_blank
end
end
end
|
=begin
This class describes triangles. An object of type triangle is defined by
3 numbers called edges, which values are between 0 and 20,
and they satisfy the following relationship:
The sum of any two numbers is greater or equal with the third number.
=end
class Triangle
def initialize(array)
@lat1 = array[0]
@lat2 = array[1]
@lat3 = array[2]
end
def is_triangle?
# Check if an object satisfies the two relantionships
if @lat1 + @lat2 <= @lat3 ||
@lat1 + @lat3 <= @lat2 ||
@lat2 + @lat3 <= @lat1 ||
@lat1 > 20 || @lat1 < 0 ||
@lat2 > 20 || @lat2 < 0 ||
@lat3 > 20 || @lat3 < 0
return false
end
return true
end
def show
# Print a triangle edges
if !self.is_triangle?
return "Is not a triangle."
end
return "#{@lat1}, #{@lat2}, #{@lat3}"
end
def type
# Return a triangle types, based on its edges
if !self.is_triangle?
return "Is not a triangle"
end
if self.is_equilateral?
return "Equilateral"
elsif self.is_isosceles?
return "Isosceles"
elsif self.is_scalene?
return "Scalene"
end
end
def is_equilateral?
# Verify if is a triangle and has all 3 edges equal.
if self.is_triangle? && @lat1 == @lat2 && @lat1 == @lat3
return true
end
return false
end
def is_isosceles?
# Verifiy if is a triangle and has any teo edges equal.
if self.is_triangle? && @lat1 == @lat2 || @lat1 == @lat3 || @lat2 == @lat3
return true
end
return false
end
def is_scalene?
# Verify if is a triangle and all 3 edges are different.
if self.is_triangle? && @lat1 != @lat2 && @lat1 != @lat3 && @lat2 != @lat3
return true
end
return false
end
def perimeter
# Returns the sum of edges.
return @lat1 + @lat2 + @lat3
end
def is_congruent_with?(triangle)
# Verify if two triangles have the same type and that they are congruent
# based on the relantionship EEE - edge-edge-edge
if self.type != triangle.type
print "Have different types, so they sure are different.\n"
return false
end
print "They have same types.\n"
triangle1 = self.sort_edges
triangle2 = triangle.sort_edges
if triangle1 != triangle2
return false
end
return true
end
def sort_edges
# Sort a list of edges
edges = [@lat1, @lat2, @lat3].sort
return edges
end
end
|
class FiatShamir
attr_accessor :p, :q, :s, :it, :n, :v, :x
def initialize(prime_p, prime_q, s, iterations)
@p = prime_p # numero secreto primo p
@q = prime_q # numero primo secreto q
@s = s # numero secreto
@it = iterations # numero de iteraciones
@n = @p * @q # numero publico N (p * q)
@v = (@s * @s) % @n # identifición pública de A
@x # numero secreto x tal que 0 < x < N
@a # testigo
@y
end
def run
for it in 0...@it
puts
puts "Iteración #{it+1}"
loop do
puts "A escoge un número secreto x tal que 0 < x < N"
@x = gets.to_i
break if (@x > 0 && @x < @n)
end
@a = (@x * @x) % @n
puts "Testigo: A envía a B a = #{@a}"
puts "Reto: B envía a A un bit e, elegido al azar, introdúcelo"
e = gets.to_i
if e == 0
@y = @x % @n
# puts "Respuesta: A envía a B y = x (mod N)"
elsif e == 1
@y = (@x * @s) % @n
# puts "Respuesta: A envía a B y = xs (mod N)"
end
if it == @it - 1
puts "Verificación: B comprueba la información recibida"
if e == 0
puts "Comprobar que y^2 = a (mod N)"
puts "N = #{@n}"
puts "v = #{@v}"
puts "a = #{@a}, comprobar que #{@y}^2, #{@y * @y} ≡ #{@a} mod #{@n} y dar por válida la iteración."
elsif e == 1
puts "Comprobar que y^2 = a*v (mod N)"
puts "N = #{@n}"
puts "v = #{@v}"
puts "a = #{@a}, comprobar que #{@y}^2, #{@y * @y} ≡ #{@a} * #{@v} mod #{@n} y dar por válida la iteración."
end
end
end
end
end
# cuando queremos comprobr si el numero es primo (para p, q introducidos por teclado)
# si prime es 2 significa que solo es divisible por 1 y por si mismo
def is_prime(number)
prime = 0
for i in 1..number
if (number % i == 0)
prime += 1
end
end
return true if prime == 2
return false
end
#algoritmo de euclides basado en modulo (tambien esta basado en resta)
# lo utilizamos para saber si dos numeros son coprimos, en cuyo caso se devuelve 1 ya que es el unico
# comun dvisor
def gcd_euclides(a, b)
while b != 0
t = b
b = a % b
a = t
end
a
end
def require_data
prime_p = 0
prime_q = 0
s = 0
loop do
puts "Introduce el número p, tiene que ser primo"
prime_p = gets.to_i
break if is_prime(prime_p)
end
loop do
puts "Introduce el número q, tiene que ser primo"
prime_q = gets.to_i
break if is_prime(prime_q)
end
n = prime_p * prime_q
loop do
puts "Introduce el valor de s (0 < s < N), tal que s y N=#{n} son coprimos"
s = gets.to_i
break if s <= 0 || s >= n || gcd_euclides(s, n) == 1
end
puts "Introduce el número de iteraciones"
iter = gets.to_i
fs_object = FiatShamir.new(prime_p, prime_q, s, iter)
# return fs_object
end
ejemplo_1 = FiatShamir.new(7, 5, 3, 2)
ejemplo_1.run
ejemplo_2 = FiatShamir.new(683, 811, 43215, 1)
ejemplo_2.run
# modificacion, mostrar solo la ultima iteración
ejemplo_clase = FiatShamir.new(977, 983, 43215, 5)
ejemplo_clase.run |
require 'net/ldap/dn'
module LDAPUtils
# https://github.com/ruby-ldap/ruby-net-ldap/issues/222
@B32 = 2**32
def self.get_sid_string(data)
sid = data.unpack('b x nN V*')
sid[1, 2] = Array[nil, b48_to_fixnum(sid[1], sid[2])]
'S-' + sid.compact.join('-')
end
def self.get_sid_strings(arr)
arr.map { |data|
get_sid_string(data)
}
end
def self.b48_to_fixnum(i16, i32)
i32 + (i16 * @B32)
end
# http://astockwell.com/blog/2015/06/active-directory-objectguid-queries-ruby-python/
def self.to_oracle_raw16(string, strip_dashes=true, dashify_result=false)
oracle_format_indices = [3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15]
string = string.gsub('-'){ |match| '' } if strip_dashes
parts = split_into_chunks(string)
result = oracle_format_indices.map { |index| parts[index] }.reduce('', :+)
if dashify_result
result = [result[0..7], result[8..11], result[12..15], result[16..19], result[20..result.size]].join('-')
end
return result
end
def self.split_into_chunks(string, chunk_length=2)
chunks = []
while string.size >= chunk_length
chunks << string[0, chunk_length]
string = string[chunk_length, string.size]
end
chunks << string unless string.empty?
return chunks
end
def self.pack_guid(string)
[to_oracle_raw16(string)].pack('H*')
end
def self.unpack_guid(hex)
to_oracle_raw16(hex.unpack('H*').first, true, true)
end
def self.unpack_guids(arr)
arr.map { |hex|
unpack_guid(hex)
}
end
def self.get_cn(dn_s)
dn = Net::LDAP::DN.new(dn_s)
dn_h = dn.enum_for(:each_pair).map { |key, value| [key.downcase, value] }.to_h
dn_h['cn']
end
def self.get_cns(dns)
dns.map { |dn_s|
get_cn(dn_s)
}
end
end |
class StdInfo < ActiveRecord::Base
attr_accessible :std_id, :std_language, :std_name_cn, :std_name_en, :std_org, :std_release_time, :std_tag1, :std_tag2, :std_path
validates :std_id, :presence => true, :uniqueness => true
validates :std_name_cn, :presence => true
validates :std_name_en, :presence => true
has_many :taggings
has_many :tags, :through => :taggings
# def self.std_path(std_id)
# StdPath.find_by_name(std_id)s
# end
def self.find_for_test
find(:all, :order => "std_id")
end
def self.find_by_tag(tag)
find_all_by_std_tag1(tag) + find_all_by_std_tag2(tag)
end
end
|
require 'test_helper'
class ApplicationHelperTest < ActionView::TestCase
test "full title helper" do
assert_equal full_title, "stokedbiz: bound to be insanely stoked"
assert_equal full_title("contact us"), "contact us | stokedbiz: bound to be insanely stoked"
end
end |
require 'rails_helper'
RSpec.describe OrderAddress, type: :model do
before do
@user = FactoryBot.build(:user)
@item = FactoryBot.build(:item)
@order = FactoryBot.build(:order_address, user_id: @user, item_id: @item)
end
context 'ユーザー登録ができる時' do
it "全ての情報があれば保存ができること" do
expect(@order).to be_valid
end
it "buildnameが空でも登録できること" do
@order.buildname = ""
expect(@order).to be_valid
end
end
context 'ユーザー登録ができない時' do
it "tokenが空では登録できないこと" do
@order.token = nil
@order.valid?
expect(@order.errors.full_messages).to include("Token can't be blank")
end
it "prefecuteres_idが空では登録できない" do
@order.prefectures_id = 0
@order.valid?
expect(@order.errors.full_messages).to include("Prefectures must be other than 0")
end
it "postalcadeが空では登録することができない" do
@order.postalcade = ''
@order.valid?
expect(@order.errors.full_messages).to include("Postalcade can't be blank")
end
it "citiesが空では登録することができない" do
@order.cities = ''
@order.valid?
expect(@order.errors.full_messages).to include("Cities can't be blank")
end
it "streetadoressが空では登録することができない" do
@order.streetadoress = ''
@order.valid?
expect(@order.errors.full_messages).to include("Streetadoress can't be blank")
end
it "phonenameがからでは登録するとこができない" do
@order.phonename = ''
@order.valid?
expect(@order.errors.full_messages).to include("Phonename can't be blank")
end
it "郵便番号はハイフン無しでは購入できないこと" do
@order.postalcade= '2543654'
@order.valid?
expect(@order.errors.full_messages).to include("Postalcade is invalid. Include hyphen(-)")
end
it "電話番号は12桁以上では購入できないこと" do
@order.phonename = '123456789012'
@order.valid?
expect(@order.errors.full_messages).to include("Phonename is too long (maximum is 11 characters)")
end
it "電話番号は英数混合では購入できないこと" do
@order.phonename = '1235689gfgyfy'
@order.valid?
expect(@order.errors.full_messages).to include("Phonename is not a number", "Phonename is too long (maximum is 11 characters)")
end
it "user_idが空だと購入できないこと" do
@order.user_id = ''
@order.valid?
expect(@order.errors.full_messages).to include("User can't be blank")
end
it "item_idが空だと購入できないこと" do
@order.item_id = ''
@order.valid?
expect(@order.errors.full_messages).to include("Item can't be blank")
end
end
end |
class JobPosting < ApplicationRecord
has_many :job_board_metros
has_many :candidates, through: :job_board_metros
end
|
class AddPractitionerIdToServices < ActiveRecord::Migration
def change
remove_column :services, :practitioner_id, :int
end
end
|
# == Schema Information
#
# Table name: app_rating_items
#
# id :integer not null, primary key
# comment :text
# rating :integer
# created_at :datetime not null
# updated_at :datetime not null
# app_rating_id :integer
# rating_item_id :integer
#
class AppRatingItem < ApplicationRecord
belongs_to :app_rating
belongs_to :rating_item
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
def create_category
arr = %w[chinese italian japanese french belgian]
arr.sample
end
def create_array
arr = []
5.times do
arr << { name: Faker::Restaurant.name, address: Faker::Address.full_address,
phone_number: Faker::PhoneNumber.cell_phone, category: create_category }
end
arr
end
puts 'Cleaning Database'
Restaurant.destroy_all
puts 'Creating restaurants...'
restaurants = create_array
restaurants.each do |attributes|
restaurant = Restaurant.create!(attributes)
review = Review.new({ content: Faker::TvShows::MichaelScott.quote, rating: rand(0..5) })
review.restaurant = restaurant
review.save!
puts "Created #{restaurant.name}"
end
puts 'Finished!'
|
# See the Pagy documentation: https://ddnexus.github.io/pagy/extras/support
# encoding: utf-8
# frozen_string_literal: true
require 'pagy/extras/shared'
class Pagy
def to_h
{ count: defined?(@count) && @count,
page: @page,
items: @items,
pages: @pages,
last: @last,
offset: @offset,
from: @from,
to: @to,
prev: @prev,
next: @next,
vars: @vars,
series: series }
end
module Frontend
def pagy_prev_url(pagy)
pagy_url_for(pagy.prev, pagy) if pagy.prev
end
def pagy_next_url(pagy)
pagy_url_for(pagy.next, pagy) if pagy.next
end
def pagy_prev_link(pagy, text = pagy_t('pagy.nav.prev'), link_extra = '')
pagy.prev ? %(<span class="page prev"><a href="#{pagy_prev_url(pagy)}" rel="next" aria-label="next" #{pagy.vars[:link_extra]} #{link_extra}>#{text}</a></span>)
: %(<span class="page prev disabled">#{text}</span>)
end
def pagy_next_link(pagy, text = pagy_t('pagy.nav.next'), link_extra = '')
pagy.next ? %(<span class="page next"><a href="#{pagy_next_url(pagy)}" rel="next" aria-label="next" #{pagy.vars[:link_extra]} #{link_extra}>#{text}</a></span>)
: %(<span class="page next disabled">#{text}</span>)
end
def pagy_serialized(pagy)
pagy.to_h.merge(prev_url: pagy_prev_url(pagy), next_url: pagy_next_url(pagy))
end
# Multi purpose JSON tag for custom javascript initialization
def pagy_apply_init_tag(pagy, function, payload=pagy_serialized(pagy))
pagy_json_tag(:applyInit, function, payload)
end
end
end
|
require 'spec_helper'
describe 'kdump_kernel_arguments fact' do
before :each do
Facter.clear
end
context 'kernel is linux' do
it 'returns output from /proc/cmdline' do
expected_value = my_fixture_read('cmdline1')
allow(Facter::Core::Execution).to receive(:exec).with('uname -s').and_return('Linux')
allow(Facter::Core::Execution).to receive(:execute).with('cat /proc/cmdline 2>/dev/null').and_return(expected_value)
expect(Facter.fact(:kdump_kernel_arguments).value).to eq(expected_value)
end
end
end
|
class CreateProjectGoals < ActiveRecord::Migration[5.2]
def change
create_table :project_goals do |t|
t.integer :project_id, null: false
t.text :content, null: false
t.datetime :by_when, null: false
t.boolean :is_private, null: false
t.timestamps
end
end
end
|
require 'pry'
require 'colorize' #using this gem for color output in terminal...
#after reviewing rock paper scissorlesson video....
#learned the loop do, loop
CHOICES = { '1' => "Paper", '2' => "Rock", '3' => "Scissors"}
CHEAT = {'5' => "BFG"}
#added a new array for the cheat for the computer...
def say(msg)
puts "\n#{msg}"
end
def winning_message
"You have beaten the mighty Hal-9000 by choosing"
end
#created winning_message so i dont have to copy and paste the same thing over again
def display_winning_message(winning_choice)
case winning_choice
when '1'
say "#{winning_message} Paper!".green
when '2'
say "#{winning_message} Rock!".green
when '3'
say "#{winning_message} Scissors!".green
when '5'
say "You lost miserably".red
say "Hal-9000 has pulled out the BFG and has obliterated your whole body.".blue
say "The BFG is an oldschool gun that beats anything. You have just been owned and tea bagged in the process!".yellow
end
end
loop do
begin
say "Please make a number selection"
print "\n1) Paper 2) Rock 3) Scissors : "
user_choice = gets.chomp
end until CHOICES.keys.include?(user_choice)
#keys gets the keys from the hash and turns in into array in this case the CHOICES hash
#include? runs a boolean to see if the user_choice matches the CHOICES array
computer_choice = CHOICES.merge(CHEAT).keys.sample
#merge is used to merge 2
#sample is used to get a random value from the array specificed
if user_choice == computer_choice
say "It's a tie, the human player has survived this dastardly Rock Paper Scissor game against almighty Hal-9000".yellow
elsif computer_choice == '5'
display_winning_message(computer_choice)
elsif user_choice == '1' && computer_choice == '2' ||
user_choice == '2' && computer_choice == '1' ||
user_choice == '3' && computer_choice == '1'
display_winning_message(user_choice)
else
say "Hal-9000 has won, you have failed against the almighty Hal-9000 because of your failure the Earth is now enslaved by Hal-9000!".red
end
say "Would you like to try again? this is the Matrix you know... "
print "Type yes to play again or no to exit the rabbit hole: "
play_again = gets.chomp.downcase
if play_again == 'no'
say "Thank you for playing please come again!"
break
else
end
end |
require 'rails_helper'
RSpec.describe InvoicingIndexDecorator do
it '#created_at' do
Timecop.travel(Time.zone.local(2008, 9, 1, 10, 5, 1)) do
property_create human_ref: 1, account: account_new
invoicing_dec = described_class.new \
invoicing_create property_range: '1-2'
expect(invoicing_dec.created_at).to eq '01 Sep 2008 10:05'
end
end
it '#period_between - displays formatted date' do
invoicing_dec = described_class.new \
invoicing_new period: '2010-3-25'..'2010-6-25'
expect(invoicing_dec.period_between).to eq '25/Mar/10 - 25/Jun/10'
end
end
|
require 'test_helper'
class UsersControllerTest < ActionController::TestCase
def test_should_get_index
get :index, {}, { :user_id => users(:fred).id }
assert_response :success
assert_not_nil assigns(:users)
end
def test_should_get_new
get :new, {}, { :user_id => users(:fred).id }
assert_response :success
end
def test_should_create_user
assert_difference('User.count') do
post :create, { :user => { :name => 'testcreate', :password => 'testpw' } }, { :user_id => users(:fred).id }
end
assert_not_nil assigns(:user)
uid = User.find_by_name('testcreate').id
assert_redirected_to :action => :assign_roles, :params => {:id => uid }
end
def test_should_show_user
get :show, {:id => users(:one).id}, { :user_id => users(:fred).id }
assert_response :success
end
def test_should_get_assign_roles
get :assign_roles, { :id => users(:fred).id }, { :user_id => users(:fred).id }
assert_response :success
end
def test_should_get_edit
get :edit, {:id => users(:one).id},{ :user_id => users(:fred).id }
assert_response :success
end
def test_should_update_user
assert_difference('User.count', 0) do
put :update, {:id => users(:one).id, :user => { :id => users(:one).id, :name => 'testupdate', :password => 'testpw' }},{ :user_id => users(:fred).id, :original_uri => users_path }
end
assert_not_nil assigns(:user)
user = User.find(users(:one).id)
assert_equal 'testupdate', user.name
assert_redirected_to users_path
end
def test_should_destroy_user
assert_difference('User.count', -1) do
delete :destroy, {:id => users(:one).id},{ :user_id => users(:fred).id }
end
assert_redirected_to users_path
end
end
|
require "rails_helper"
describe Toolbox::Tools::Dictionary do
it "appears in the list of tools" do
expect(Toolbox::Tools.all).to include Toolbox::Tools::Dictionary
end
context '#will_handle' do
[
{ matches: true, text: "define sauce" },
{ matches: true, text: "define pasta sauce" },
{ matches: false, text: "define" },
{ matches: false, text: "sauce" }
].each do |test_data|
matches = test_data[:matches]
text = test_data[:text]
it "#{matches ? 'matches' : 'does not match'} '#{text}'" do
if(matches)
expect(Toolbox::Tools::Dictionary.will_handle.match(text)).not_to be_nil
else
expect(Toolbox::Tools::Dictionary.will_handle.match(text)).to be_nil
end
end
end
end
context '#help_text' do
it "returns useful help text" do
expect(Toolbox::Tools::Dictionary.help_text).to eq("define <word>")
end
end
context '#handle', vcr: true do
it "returns the definition of a word with its domain" do
result = Toolbox::Tools::Dictionary.new('define uranium').handle
expect(result).to eq(URANIUM_DEFINITION)
end
it "returns multiple definitions in a numbered list, and includes domains when they exist" do
result = Toolbox::Tools::Dictionary.new('define sound').handle
expect(result).to eq(SOUND_DEFINITION)
end
it "suggests a root word if the word is not found and is an inflection" do
result = Toolbox::Tools::Dictionary.new('define reversing').handle
expect(result).to eq(REVERSING_INFLECTION)
end
it "suggests a root word only once (removing duplicates) if the word is not found and is an inflection" do
result = Toolbox::Tools::Dictionary.new('define cats').handle
expect(result).to eq(CATS_INFLECTION)
end
it "doesn't blow up when there are empty entries in the results (e.g. defining 'cat')" do
result = Toolbox::Tools::Dictionary.new('define cat').handle
expect(result).to eq(CAT_DEFINITION)
end
it "suggests an alternate spelling if the word is not found and is not an inflection" do
result = Toolbox::Tools::Dictionary.new('define absolout').handle
expect(result).to eq(ABSOLOUT_ALTERNATIVES)
end
it "returns a help message if a word is not found and it is not an inflexion and has no alternate spellings" do
result = Toolbox::Tools::Dictionary.new('define sdffdsdsfa').handle
expect(result).to eq(WORD_NOT_FOUND_MESSAGE)
end
it "returns a help message if the API is offline" do
# Fiddled with the VCR for this spec so it returns an error response
result = Toolbox::Tools::Dictionary.new('define offline').handle
expect(result).to eq("There was a problem connecting to the dictionary api")
end
end
end
CATS_INFLECTION = "Did you mean
- cat".freeze
REVERSING_INFLECTION = "Did you mean
- reverse".freeze
ABSOLOUT_ALTERNATIVES = "Did you mean
- absonous
- absolute".freeze
WORD_NOT_FOUND_MESSAGE = "🤦 Wow, that's not even close to a real word.".freeze
URANIUM_DEFINITION = "NOUN
Element: the chemical element of atomic number 92, a dense grey radioactive metal used as a fuel in nuclear reactors.".freeze
CAT_DEFINITION = "NOUN
1. a) Mammal: a small domesticated carnivorous mammal with soft fur, a short snout, and retractable claws. It is widely kept as a pet or for catching mice, and many breeds have been developed.
1. b) Jazz: (especially among jazz enthusiasts) a man
1. c) Games: a short tapered stick used in the game of tipcat.
VERB
1. Nautical: raise (an anchor) from the surface of the water to the cathead
RESIDUAL
1. a) Computing: computer-assisted (or -aided) testing.
1. b) Aviation: clear air turbulence.".freeze
SOUND_DEFINITION = "NOUN
1. a) Physics: vibrations that travel through the air or another medium and can be heard when they reach a person's or animal's ear
1. b) Music: sound produced by continuous and regular vibrations, as opposed to noise.
1. c) Film, Video: music, speech, and sound effects when recorded and used to accompany a film, video, or broadcast
1. d) An idea or impression conveyed by words
2. Surgery: a long surgical probe, typically with a curved, blunt end.
3. Geography: a narrow stretch of water forming an inlet or connecting two wider areas of water such as two seas or a sea and a lake.
VERB
1. a) Emit or cause to emit sound
1. b) Convey a specified impression when heard
2. a) Nautical: ascertain (the depth of water in the sea, a lake, or a river), typically by means of a line or pole or using sound echoes
2. b) Question (someone) discreetly or cautiously so as to ascertain their opinions on a subject
2. c) Medicine: examine (a person's bladder or other internal cavity) with a long surgical probe.
2. d) Zoology: (especially of a whale) dive down steeply to a great depth
ADJECTIVE
1. a) In good condition; not damaged, injured, or diseased
1. b) Based on valid reason or good judgement
1. c) (of sleep) deep and undisturbed
1. d) (of a beating) severe
ADVERB
1. Soundly".freeze
|
class AllowNullVariantPrice < ActiveRecord::Migration
def self.up
change_column :variants, :price, :decimal, :precision => 8, :scale => 2, :null => true
end
def self.down
change_column :variants, :price, :decimal, :precision => 8, :scale => 2, :null => false
end
end
|
require 'spec_helper'
describe Panel do
context "with no fields" do
let(:panel) { Panel.new }
it "saves the record" do
panel.save.should be_true # false positive, catches it later
end
end
context "with one field" do
let(:panel) { Panel.new(:title => "Test Panel") }
it "does not save the record" do
panel.save.should be_false
end
end
context "with two fields" do
let(:panel) { Panel.new(:title => "Test Panel", :panel => "test-panel.png") }
it "does not save the record" do
panel.save.should be_false
end
end
context "with three fields" do
let(:panel) { Factory.build(:panel) }
it "saves the record" do
panel.save.should be_true
end
end
describe "#has_any_attributes?" do
context "with no fields" do
let(:panel) { Panel.new }
it "returns false" do
panel.has_any_attributes?.should be_false
end
end
context "with one field" do
let(:panel) { Panel.new(:title => "Test Panel") }
it "returns true" do
panel.has_any_attributes?.should be_true
end
end
context "with two fields" do
let(:panel) { Panel.new(:title => "Test Panel", :panel => "test-panel.png") }
it "returns true" do
panel.has_any_attributes?.should be_true
end
end
context "with three fields" do
let(:panel) { Factory.build(:panel) }
it "returns true" do
panel.has_any_attributes?.should be_true
end
end
end
describe ".overwrite_existing" do
context "with no existing panels" do
before(:each) do
@panels = []
["Left", "Right Top", "Right Bottom"].each do |position|
@panels << Factory.build(:panel, :position => position)
end
end
it "saves all three panels" do
expect { Panel.overwrite_existing(@panels) }.to change(Panel, :count).from(0).to(3)
end
end
context "updating one panel" do
before(:each) do
["Left", "Right Top", "Right Bottom"].each_with_index do |position, index|
Factory(:panel, :title => "Panel #{index}", :position => position)
end
panels = [Factory.build(:panel, :title => "Panel 3", :position => "Left")]
Panel.overwrite_existing(panels)
end
it "updates only that panel" do
Panel.find_by_position("Left").title.should == "Panel 3"
end
it "does not change the other two panels" do
Panel.find_by_position("Right Top").title.should == "Panel 1"
Panel.find_by_position("Right Bottom").title.should == "Panel 2"
end
it "only saves three records" do
Panel.count.should == 3
end
end
context "updating two panels" do
before(:each) do
["Left", "Right Top", "Right Bottom"].each_with_index do |position, index|
Factory(:panel, :title => "Panel #{index}", :position => position)
end
panels = []
count = 3
["Left", "Right Top"].each do |position|
panels << Factory.build(:panel, :title => "Panel #{count}", :position => position)
count = count+1
end
Panel.overwrite_existing(panels)
end
it "updates only those two panels" do
Panel.find_by_position("Left").title.should == "Panel 3"
Panel.find_by_position("Right Top").title.should == "Panel 4"
end
it "does not change the other panel" do
Panel.find_by_position("Right Bottom").title.should == "Panel 2"
end
it "only saves three records" do
Panel.count.should == 3
end
end
context "updating all panels" do
before(:each) do
["Left", "Right Top", "Right Bottom"].each_with_index do |position, index|
Factory(:panel, :title => "Panel #{index}", :position => position)
end
panels = []
count = 3
["Left", "Right Top", "Right Bottom"].each do |position|
panels << Factory.build(:panel, :title => "Panel #{count}", :position => position)
count = count+1
end
Panel.overwrite_existing(panels)
end
it "updates all three panels" do
Panel.find_by_position("Left").title.should == "Panel 3"
Panel.find_by_position("Right Top").title.should == "Panel 4"
Panel.find_by_position("Right Bottom").title.should == "Panel 5"
end
it "only saves three records" do
Panel.count.should == 3
end
end
end
end
|
class Song < ApplicationRecord
has_many :album_songs
has_many :albums, through: :album_songs
has_many :song_artists
has_many :artists, through: :song_artists
validates :name, presence: {message: "Debe tener nombre."}, length: {in: 3..20}, uniqueness: {message: "La cancion ya existe"}
validates :duration, numericality: true
validates :genre, inclusion: {in: %w(Alternative-Rock Blues Classical Country Electronic Funk Heavy-Metal Hip-Hop Jazz Pop Reggae Soul Rock),
message: "%{value} no es un genero valido."}, allow_nil: true
end
|
# == Schema Information
#
# Table name: activities
#
# id :integer not null, primary key
# name :string(255)
# address :string(255)
# phone :string(255)
# biz_url :string(255)
# thumbnail_photo :string(255)
# rating :string(255)
# created_at :datetime
# updated_at :datetime
# trip_id :integer
# yid :string(255)
#
class Activity < ActiveRecord::Base
belongs_to :trip
validates :name, presence: true
end
|
class ContactMailer < ActionMailer::Base
default from: "no-reply@ski-lines.com"
def contact_form_submit(contact)
@contact = contact
@url = 'https://www.ski-lines.com'
mail(to: 'mark@ski-lines.com', subject: 'New Contact Form Submission')
end
end
|
class Song < ActiveRecord::Base
belongs_to :user, required: true
has_many :playlists
has_many :added_by, through: :playlists, source: :user
validates :title, :artist, presence: true, length:{minimum: 2}
end
|
require 'rails_helper'
RSpec.describe PaymentIndexDecorator do
let(:source) { payment_new }
let(:decorator) { described_class.new source }
describe 'attributes' do
it '#amount' do
expect(decorator.amount).to eq '£88.08'
end
end
end
|
class List < ActiveRecord::Base
include PublicActivity::Common
validates_presence_of :title
belongs_to :user
delegate :username, to: :user
has_many :tasks, dependent: :destroy
accepts_nested_attributes_for :tasks, allow_destroy: true, reject_if: proc { |attributes| attributes['title'].blank? }
end
|
Gem::Specification.new do |s|
s.name = 'bicycle_report'
s.version = '0.0.0'
s.platform = Gem::Platform::RUBY
s.authors = ['Mateusz Konieczny']
s.email = ['matkoniecz@gmail.com']
s.homepage = 'https://github.com/matkoniecz/bicycle_report'
s.summary = 'Generates bicycle reports from OSM data.'
s.description = 'Generates bicycle reports from OSM data.'
s.license = 'GPL v3'
s.required_rubygems_version = '>= 1.8.23'
s.add_dependency 'i18n', '~> 0.6.6'
s.add_dependency 'leafleter', '~>0'
s.add_dependency 'overhelper', '~>0'
s.add_dependency 'rest-client', '~>1'
s.add_dependency 'persistent-cache', '~>0'
#digest/sha1 is from stdlib
s.add_development_dependency 'rspec', '~>3'
s.add_development_dependency 'matkoniecz-ruby-style'
# If you need to check in files that aren't .rb files, add them here
s.files = Dir['{lib}/**/*.rb', 'bin/*', '*.txt', '*.md']
s.require_path = 'lib'
end
=begin
how to release new gem version:
gem build bicycle_report.gemspec
gem install bicycle_report-*.*.*.gem
gem push bicycle_report-*.*.*.gem
=end |
module ActivityHelpers
def page_displays_an_activity(activity_presenter:)
click_on t("tabs.activity.details")
expect(page).to have_content t("activerecord.attributes.activity.organisation")
expect(page).to have_content activity_presenter.organisation.name
expect(page).to have_content t("activerecord.attributes.activity.level")
expect(page).to have_content activity_presenter.level
unless activity_presenter.fund?
expect(page).to have_content t("activerecord.attributes.activity.parent")
expect(page).to have_content activity_presenter.parent_title
end
expect(page).to have_content t("activerecord.attributes.activity.partner_organisation_identifier")
expect(page).to have_content activity_presenter.partner_organisation_identifier
expect(page).to have_content custom_capitalisation(t("activerecord.attributes.activity.title", level: activity_presenter.level))
expect(page).to have_content activity_presenter.title
expect(page).to have_content t("activerecord.attributes.activity.description")
expect(page).to have_content activity_presenter.description
expect(page).to have_content t("activerecord.attributes.activity.sector", level: activity_presenter.level)
expect(page).to have_content activity_presenter.sector
unless activity_presenter.fund?
expect(page).to have_content t("activerecord.attributes.activity.programme_status")
expect(page).to have_content activity_presenter.programme_status
end
expect(page).to have_content t("activerecord.attributes.activity.planned_start_date")
expect(page).to have_content activity_presenter.planned_start_date
expect(page).to have_content t("activerecord.attributes.activity.planned_end_date")
expect(page).to have_content activity_presenter.planned_end_date
expect(page).to have_content t("activerecord.attributes.activity.actual_start_date")
expect(page).to have_content activity_presenter.actual_start_date
expect(page).to have_content t("activerecord.attributes.activity.actual_end_date")
expect(page).to have_content activity_presenter.actual_end_date
expect(page).to have_content t("activerecord.attributes.activity.benefitting_countries")
expect(page).to have_content activity_presenter.recipient_region
expect(page).to have_content t("activerecord.attributes.activity.aid_type")
expect(page).to have_content activity_presenter.aid_type
end
def associated_fund_is_newton?(activity)
return if activity.nil?
activity.associated_fund.roda_identifier == "NF"
end
end
|
class Article < ActiveRecord::Base
belongs_to :author, class_name: 'User'
has_many :comments, dependent: :destroy
def authored_by?(someone)
author == someone
end
end
|
class Reg < ApplicationRecord
has_secure_password
self.primary_key = 'Regid'
validates :Regid, :presence => {:message => "cannot be blank ..."}
validates_uniqueness_of :Regid
validates_uniqueness_of :Emailid
validates :name, :presence => {:message => "cannot be blank ..."}
validates :contactno, :presence => {:message => "cannot be blank ..."}
validates :Emailid, :presence => {:message => "cannot be blank ..."}
validates :currentsemester, :presence => {:message => "cannot be blank ..."}
validates_format_of :Emailid, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
end
|
class AddStartedAtToMatches < ActiveRecord::Migration
def change
add_column :matches, :started_at, :datetime, null: false, after: :name
end
end
|
require 'rails_helper'
feature 'User Authentication' do
scenario 'allows a user to signup' do
visit '/'
expect(page).to have_link('Signup')
click_link 'Signup'
fill_in 'First name', with: 'bob'
fill_in 'Last name', with: 'smith'
fill_in 'Email', with: 'bob@smith.com'
fill_in 'Password', with: 'sup3rs3krit'
fill_in 'Password confirmation', with: 'sup3rs3krit'
click_button 'Signup'
expect(page).to have_text('Thank you for signing up Bob')
expect(page).to have_text('bob@smith.com')
end
scenario 'allows existing users to login' do
user = FactoryGirl.create(:user)
visit '/'
expect(page).to have_link('Login')
click_link('Login')
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
click_button 'Login'
expect(page).to have_text("Welcome back #{user.first_name.titleize}")
expect(page).to have_text(user.email)
end
scenario 'does not allow existing users to login with an invalid password' do
user = FactoryGirl.create(:user, password: 'Sup3rS3krit')
visit '/'
expect(page).to have_link('Login')
click_link('Login')
fill_in 'Email', with: user.email
fill_in 'Password', with: 'NOT_YOUR_PASSWORD'
click_button 'Login'
expect(page).to have_text('Invalid email or password')
end
scenario 'allows a logged in user to logout' do
user = FactoryGirl.create(:user, password: 'Sup3rS3krit')
visit '/'
expect(page).to have_link('Login')
click_link('Login')
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
click_button 'Login'
expect(page).to have_text(user.email)
expect(page).to have_link('Logout')
click_link('Logout')
expect(page).to have_text("#{user.email} has been logged out")
expect(page).to_not have_text("Welcome back #{user.first_name.titleize}")
expect(page).to_not have_text("Signed in as #{user.email}")
end
scenario 'allow a logged in user to claim a car' do
user = FactoryGirl.create(:user)
car1 = FactoryGirl.create(:car)
car2 = FactoryGirl.create(:car)
visit login_path
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
click_button 'Login'
within("#car_#{car1.id}") do
click_link 'Claim'
end
expect(page).to have_text("#{car1.make} #{car1.model} has been saved to your inventory.")
expect(page).to_not have_selector("#car_#{car1.id}")
expect(page).to have_selector("#car_#{car2.id}")
expect(page).to have_link('My Cars')
click_link 'My Cars'
expect(page).to have_selector("#car_#{car1.id}")
expect(page).to_not have_selector("#car_#{car2.id}")
end
scenario 'allow a logged in user to unclaim a car' do
user = FactoryGirl.create(:user)
car1 = FactoryGirl.create(:car, user: user)
car2 = FactoryGirl.create(:car)
visit login_path
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
click_button 'Login'
visit my_cars_path
within("#car_#{car1.id}") do
click_link 'UnClaim'
end
expect(page).to have_text("#{car1.make} #{car1.model} has been removed from your inventory.")
expect(page).to_not have_selector("#car_#{car1.id}")
expect(page).to_not have_selector("#car_#{car2.id}")
expect(page).to have_link('Cars')
click_link 'Cars'
expect(page).to have_selector("#car_#{car1.id}")
expect(page).to have_selector("#car_#{car2.id}")
end
scenario 'show/hide My Cars link based on user being logged in' do
user = FactoryGirl.create(:user)
visit root_path
expect(page).to have_link('Cars')
expect(page).to_not have_link('My Cars')
visit login_path
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
click_button 'Login'
expect(page).to have_link('Cars')
expect(page).to have_link('My Cars')
end
end
|
class User < ApplicationRecord
has_secure_password
has_many :appointments
has_many :events, through: :appointments
def upcoming_events
events.all.select do |event|
event.start_time > Time.now
end
end
end
|
require 'digest/md5'
module Wechaty
def self.sign(params)
key = params.delete(:key)
query = params.sort.map do |key, value|
"#{key}=#{value}" if value != "" && !value.nil?
end.compact.join('&')
Digest::MD5.hexdigest("#{query}&key=#{key || Wechaty.config.api_key}").upcase
end
def self.verify?(params)
params = params.dup
sign = params.delete('sign') || params.delete(:sign)
sign(params) == sign
end
end
|
# == Schema Information
#
# Table name: bwc_codes_group_retro_tiers
#
# id :integer not null, primary key
# discount_tier :float
# industry_group :integer
# public_employer_only :boolean default(FALSE)
# created_at :datetime not null
# updated_at :datetime not null
#
FactoryBot.define do
factory :bwc_codes_group_retro_tier do
end
end
|
module Locomotive
class EditableSelectInput < SimpleForm::Inputs::CollectionSelectInput
def link(wrapper_options)
if _options = options[:manage_collection]
label = _options[:label] || I18n.t(:edit, scope: 'locomotive.shared.form.select_input')
url = _options[:url]
template.link_to(label, url)
else
''
end
end
end
end
|
require 'csv'
module Parser
ASSETS_PATH = Rails.root.join('app/assets/')
CSV_PATH = Rails.root.join('app/assets/csv')
CSV_UPLOAD_PATH = Rails.root.join('app/assets/csv/upload')
CSV_EXPORT_PATH = Rails.root.join('app/assets/csv/export')
FILE_ROOTS = [CSV_PATH, CSV_EXPORT_PATH,CSV_EXPORT_PATH,CSV_UPLOAD_PATH].map{|p| p.to_s}
def isFileRoot path
current_root = path.gsub(path.split('/')[-1],'').gsub(/\/$/,'')
puts("Global: Path = "+current_root)
return FILE_ROOTS.include?(current_root)
end
def createhash row, avoid_nil, exclude_str='' #(array) row = [["name", "jack"],["goognight_user_id"],["ip", "223.140.238.128"], ["intro", nil], ["id", "2941471"] ,["email", "o8q4@yahoo.com.tw"], ["google_email", nil], ["device_platform", "iOS"]]
if avoid_nil
row = row.select{
|d| d[1]!=nil
}
end
if exclude_str!=''
row = row.select{
|d| d[0]!=nil&&d[1]!= exclude_str
}
end
row = row.select{
|d| d[0]!=nil
}
begin
r = Hash[
row.map do |p|
[p[0],p[1]]
end
]
return r
rescue=>exception
puts exception
end
end
def read_hash_from io,avoid_nil
puts("[CSVParser]Loading hash from csv...")
data = []
file_path = File.join(Global::CSV_UPLOAD_PATH,io.to_s)
path = (File.exists?(file_path)? Global::CSV_UPLOAD_PATH : Global::CSV_EXPORT_PATH)
Dir.chdir(path) do
print(' ')
puts(file_path)
CSV.foreach(io,headers: true,encoding: "iso-8859-1:utf-8") do |row|
row.each do |d|
if d[0]
d[0] = d[0].strip
d[0] = d[0].downcase
d[0] = d[0].gsub('','')
end
d[1] = d[1].strip if d[1]
d[1] = '' if d[1]=='..'
end
hsh = createhash row, avoid_nil
data.push(hsh)
end
end
return data
end
def check_exports
if !File.exists?(Global::CSV_EXPORT_PATH)
puts("[CSVParser]Detected export does not exist. Creating.")
Dir.mkdir(Global::CSV_EXPORT_PATH)
puts("[CSVParser]Created")
end
end
def export_africa hash_arr,file_name
check_exports
Dir.chdir(Global::CSV_EXPORT_PATH) do
fn = file_name.gsub(' ','_').gsub('+','_plus').split('.')[0]+'_' + DateTime.now.in_time_zone('Taipei').strftime("%m-%d_%H-%M") +'.csv'
longest_hash = hash_arr.max_by(&:length)
puts "=============================="
puts hash_arr
puts "=============================="
CSV.open(fn,'w') do |row|
row << longest_hash.keys
hash_arr.each do |hash|
row<<hash.values
end
end
return fn
end
end
def get_full_csv_path file_name
file_path = File.join(Global::CSV_UPLOAD_PATH,file_name)
path = (File.exists?(file_path)? Global::CSV_UPLOAD_PATH : Global::CSV_EXPORT_PATH)
return Rails.root.join(path,file_name)
end
end |
# frozen_string_literal: true
module Guard
class I18nJson < Plugin
VERSION = "0.0.1"
end
end
|
class SessionsController < ApplicationController
def new
end
def create
user = User.where(email: params[:session][:email]).first
if user && user.authenticate(params[:session][:password])
login_as(user) && redirect_to(url_after_login, notice: t("sessions.create.notice"))
else
flash.now.alert = t("sessions.create.invalid")
render action: "new"
end
end
def destroy
session[:user_id] = nil
redirect_to url_after_logout, notice: t("sessions.destroy.notice")
end
private
def session_params
params.required(:session).permit(:email, :password)
end
end
|
require "rails_helper"
RSpec.describe "Static", :type => :request do
before(:each) do
objects = RequestsHelper.prepare_requests()
@user = objects[:user]
end
it "receives a feed after correct token" do
get "/feed", headers: {
'Accept' => 'application/json',
'Authorization' => "Token #{@user.token}"
}
# Konwertujemy JSON
json = JSON(response.body)
expect(response).to have_http_status(200)
expect(json.keys).to contain_exactly('movies')
end
it "leads to acces denied after wrong token" do
get "/feed", headers: {
'Accept' => 'application/json',
'Authorization' => "Token wrongToken"
}
@expected = {
:errors => [{:detail => "Access denied"}]
}.to_json
expect(response).to have_http_status(401)
expect(response.body).to eq @expected
end
end
|
# CRUD вариантов товара
class Admin::VariantsController < Admin::BaseController
include MultilingualController
before_action :set_variant, only: [:show, :edit, :update, :destroy]
before_action :set_good, only: [:new, :edit, :create, :update, :destroy]
# GET /variants
# GET /variants.json
def index
@variants = Variant.all
end
# GET /variants/1
# GET /variants/1.json
def show
end
# GET /variants/new
def new
@variant = Variant.new
@variant.good = @good
end
# GET /variants/1/edit
def edit
end
# POST /variants
# POST /variants.json
def create
@variant = Variant.new(variant_params)
@variant.good = @good
respond_to do |format|
if @variant.save
format.html { redirect_to edit_admin_good_url(@variant.good, anchor: "variants"), notice: 'Variant was successfully created.' }
format.json { render action: 'show', status: :created, location: @variant }
else
format.html { render action: 'new' }
format.json { render json: @variant.errors, status: :unprocessable_entity }
end
end
end
def order
errors = []
if order_params
order_params.each_with_index do |id, weight|
item = Variant.find id
item.weight = weight
unless item.save
errors << item.errors
end
end
end
respond_to do |format|
if errors.empty?
format.json { head :no_content }
else
format.json { render json: errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /variants/1
# PATCH/PUT /variants/1.json
def update
respond_to do |format|
if @variant.update(variant_params)
format.html { redirect_to edit_admin_good_url(@variant.good, anchor: "variants"), notice: 'Variant was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @variant.errors, status: :unprocessable_entity }
end
end
end
# DELETE /variants/1
# DELETE /variants/1.json
def destroy
@variant.destroy
respond_to do |format|
format.html { redirect_to edit_admin_good_url(@variant.good, anchor: "variants") }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_variant
@variant = Variant.find(params[:id])
end
def set_good
if @variant.nil?
@good = Good.find(params[:good_id] || variant_params[:good_id])
else
@good = @variant.good
end
end
def safe_params
[
:good_id,
:price,
:name,
:picture,
:material,
:suffix,
:material_name,
:is_material
]
end
# Never trust parameters from the scary internet, only allow the white list through.
def variant_params
# перебираются типы свойств товара,
# проставляются свойства исходя из пришедших в параметрах
# обсуждалось, что этот функционал будет не нужен, т.к. во многом упростили схему
property_types = {}
params[:variant][:property_types].permit!.each{|k, p| property_types[k] = p[:property_id]}
params.require(:variant).permit(:is_material)
params = permit_params
params[:property_types] = property_types
[:picture, :material].each do |i|
params[i] = nil if params[i] == ''
end
params
end
def order_params
params.require(:order)
end
end
|
ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10, "Marilyn" => 22, "Spot" => 237}
p ages.values.sum
p ages.values.reduce(:+)
total_ages = 0
ages.each { |_,age| total_ages += age }
p total_ages
total_ages = 0
ages.each do |_, age|
total_ages += age
end
p total_ages |
require 'rails_helper'
RSpec.describe Beer, type: :model do
let!(:style) { FactoryGirl.create :style, name:"Lager" }
it "is created when name and style are set" do
beer = Beer.create name:"Test Beer", style:style
expect(beer).to be_valid
expect(Beer.count).to eq(1)
end
it "is not created when name is empty and style is set" do
beer = Beer.create style:style
expect(beer).not_to be_valid
expect(Beer.count).to eq(0)
end
it "is not created when style is empty and name is set" do
beer = Beer.create name:"Test Beer"
expect(beer).not_to be_valid
expect(Beer.count).to eq(0)
end
end
|
require('minitest/autorun')
require_relative('../room')
require_relative('../guest')
require_relative('../song')
class TestRoom < MiniTest::Test
def setup
@room = Room.new("Prince", 2)
@guest1 = Guest.new("Steve", 20.00)
guest2 = Guest.new("Bob", 20.00)
guest3 = Guest.new("Alan", 20.00)
@group1 = [@guest1, guest2, guest3]
@song1 = Song.new("Don't Stop Me Now", "Queen")
end
def test_check_room_has_name()
assert_equal("Prince", @room.name())
end
def test_check_room_has_size()
assert_equal(2, @room.size())
end
def test_add_guest_to_room()
@room.add_guest_to_room(@guest1)
assert_equal(1, @room.guests().count())
end
def test_remove_guest_from_room()
@room.add_guest_to_room(@guest1)
@room.remove_guest_from_room(@guest1)
assert_equal(0, @room.guests().count())
end
def test_add_group_of_guests()
@room.add_group_of_guests_to_room(@group1)
assert_equal(3, @room.guests().count())
end
def test_remove_group_of_guests()
guest = Guest.new("Kate", 20.00)
@room.add_guest_to_room(guest)
@room.add_group_of_guests_to_room(@group1)
@room.remove_group_of_guests_from_room(@group1)
assert_equal(1, @room.guests().count())
end
def test_add_song_to_room()
@room.add_song_to_room(@song1)
assert_equal(1, @room.songs().count())
end
def test_remove_song_from_room()
@room.add_song_to_room(@song1)
@room.remove_song_from_room(@song1)
assert_equal(0, @room.songs().count())
end
def test_reset_room()
@room.add_group_of_guests_to_room(@group1)
@room.add_song_to_room(@song)
@room.reset_room()
assert_equal(0, @room.songs().count())
assert_equal(0, @room.guests().count())
end
end
|
#! /usr/bin/env ruby
# vim:
def say_hello
puts "hello!"
end
alias :again :say_hello
say_hello
again
def say_hello
puts "hello! #2"
end
say_hello
again
|
# -*- encoding: utf-8 -*-
require File.dirname(__FILE__) + '/lib/omniauth-google-authenticator/version'
Gem::Specification.new do |gem|
gem.add_runtime_dependency 'omniauth', '>= 1.3.2'
gem.add_development_dependency 'maruku', '~> 0.6'
gem.add_development_dependency 'simplecov', '~> 0.4'
gem.add_development_dependency 'rack-test', '~> 0.5'
gem.add_development_dependency 'rake', '~> 13.0'
gem.name = 'omniauth-google-authenticator'
gem.version = OmniAuth::GoogleAuthenticator::VERSION
gem.description = %q{Internal Google authentication handlers for OmniAuth.}
gem.summary = gem.description
gem.email = ['justin+github@overstuffedgorilla.com']
gem.homepage = 'http://github.com/jsmestad/omniauth-google-authentication'
gem.authors = ['Justin Smestad']
gem.executables = `git ls-files -- bin/*`.split("\n").map{|f| File.basename(f)}
gem.files = `git ls-files`.split("\n")
gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
gem.require_paths = ['lib']
gem.required_rubygems_version = Gem::Requirement.new('>= 1.3.6') if gem.respond_to? :required_rubygems_version=
end
|
shared = proc do
let(:rack_key_value) { :Value }
let(:default_env) do
{
'REQUEST_METHOD' => 'GET',
'SERVER_NAME' => 'example.org',
'SERVER_PORT' => '80',
'PATH_INFO' => '/',
'rack.url_scheme' => 'http'
}
end
let(:expected_value) { rack_key_value }
let(:env) { default_env.merge(rack_key => rack_key_value) }
let(:object) { described_class.new(env) }
end
shared_examples_for 'a rack env accessor' do
instance_eval(&shared)
it { should eql(expected_value) }
it 'should not freeze the input env' do
subject
expect(env.frozen?).to be(false)
end
end
shared_examples_for 'an invalid rack env accessor' do
instance_eval(&shared)
it 'should raise error' do
expect { subject }.to raise_error(Request::Rack::InvalidKeyError, expected_message)
end
end
|
class AddPaymentProductIdToSpreeGlobalCollectCheckout < ActiveRecord::Migration
def change
add_column :spree_global_collect_checkouts, :payment_product_id, :integer
end
end
|
class AddChapteridToAnswerSpaces < ActiveRecord::Migration[5.2]
def change
add_column :answer_spaces, :chapter_id, :string, after: :user_answer
end
end
|
class Bid < ActiveRecord::Base
validates_inclusion_of :price, :in => 100..500, message: "The price must be an integer > 100 and <= 500"
validates :phone_number, :alias, presence: true
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.