repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
petertseng/adventofcode-rb-2019
04_password.rb
<reponame>petertseng/adventofcode-rb-2019<gh_stars>10-100 def increasing_between(min, max) max_digits = max.digits.reverse digits = min.digits.reverse _, decrease = digits.each_cons(2).with_index.find { |(a, b), i| a > b } # If min doesn't already meet criteria, # construct the first number that does. # For example 123411 would turn into 123444 if decrease digits = digits.take(decrease) + [digits[decrease]] * (digits.size - decrease) end Enumerator.new { |y| # You can't use > to compare arrays, but you can <=> them. until (digits <=> max_digits) > 0 y << digits.dup # Increasing digits never jeopardises increasing status, # unless nines roll over into zeroes. # Check for nines, and change them to the next increasing. # For example, 123999 would turn into 124444 non_nine = -1 non_nine -= 1 while digits[non_nine] == 9 new_digit = digits[non_nine] + 1 (non_nine..-1).each { |i| digits[i] = new_digit } end } end range = case ARGV.size when 0 ARGF.read.split(?-) when 1 (/^\d+-\d+$/.match?(ARGV[0]) ? ARGV[0] : ARGF.read).split(?-) else ARGV end min, max = range.map(&method(:Integer)) # We already know digits are non-decreasing, # so we can just count the occurrences of each digit, # and not worry about occurrences being separated! increasing = increasing_between(min, max).map { |x| x.tally.values } puts increasing.count { |d| d.any? { |x| x >= 2 } } puts increasing.count { |d| d.include?(2) }
petertseng/adventofcode-rb-2019
satadd.rb
(0..3).each { |x| (0..3).each { |y| expected = [x + y, 3].min a = x & 0xa b = x & 0x5 c = y & 0xa d = y & 0x5 bd = b & d upper_bits = a | c | (bd << 1) al = a >> 1 cl = c >> 1 lower_bits = (b ^ d) | (al & cl) | (bd & (al | cl)) #lower_bits = ((b | d) & (al | cl | ~bd)) | (al & cl) got = upper_bits | lower_bits if got != expected nb = ->n { "#{n} (#{n.to_s(2).rjust(2, ?0)})" } puts "#{nb[x]} + #{nb[y]}: Got #{nb[got]}, want #{nb[expected]}" end } }
zivolution921/meobox
app/controllers/users_controller.rb
class UsersController < ApplicationController before_action :require_signin, except: [:new, :create] before_action :require_correct_user, only: [:edit, :update, :destroy] before_action :set_plan, only: [:show, :history] def new @user = User.new end def create @user = User.new(user_params) if @user.save session[:user_id] = @user.id redirect_to root_path, notice: "Thanks for signing up!" else render :new end end def edit end def update if @user.update(user_params) redirect_to @user, notice: "Account successfully updated!" # redirect_to "/users/#{@user.id}" end end def index @users = User.all end def show @user = User.find(params[:id]) end def destroy @user.destroy session[:user_id] = nil redirect_to root_url, alert: "Account successfully deleted!" end def history if current_user.admin? @shipped_boxes = Box.where(shipped: true) else @shipped_boxes = @plan.boxes.where(shipped: true) if @plan end end private def set_plan @plan = current_user.plan end def require_correct_user @user = User.find(params[:id]) unless current_user == @user redirect_to root_url puts "PARAMS: #{params.inspect}" item_attrs = params[:box][:item_attribuets].values.map { |attr| attr } end end def user_params params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :avatar) end end
zivolution921/meobox
app/models/user.rb
<reponame>zivolution921/meobox<gh_stars>0 class User < ActiveRecord::Base attr_accessor :reset_token after_create :create_reset_digest has_secure_password has_one :registration has_one :plan, through: :registration has_many :boxes, through: :plan has_attached_file :avatar, default_url: ':style/default.png', styles: { thumb: "100x100>" } validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/ validates_presence_of :first_name, :last_name, :email after_create :create_plan # when user created plan must be created # do not override a plan def create_plan Plan.create(user_id: id) if plan.nil? end # Returns the hash digest of the given string. def self.digest(string) cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost BCrypt::Password.create(string, cost: cost) end # Returns a random token. def self.new_token SecureRandom.urlsafe_base64 end # Sends activation email. def send_activation_email UserMailer.account_activation(self).deliver_now end # Sets the password reset attributes. def create_reset_digest puts "inside create reset digest" self.reset_token = User.new_token update_attribute(:reset_digest, User.digest(reset_token)) update_attribute(:reset_sent_at, Time.zone.now) end # Sends password reset email. def send_password_reset_email UserMailer.password_reset(self).deliver_now end # Returns true if a password reset has expired. def password_reset_expired? reset_sent_at < 2.hours.ago end def self.authenticate(email, password) user = User.find_by(email: email) user && user.authenticate(password) end def already_registered_for?(plan) Registration.where(user_id: self.id, plan_id: plan.id).present? end def already_registered_for_any_plan? Registration.where(user_id: self.id).present? end def admin? admin == true end def self.sign_in_from_omniauth(auth) find_by(provider: auth['provider'], uid: auth['uid']) || create_user_from_omniauth(auth) end def self.from_omniauth(auth) where(provider: auth.provider, uid: auth.uid).first_or_initialize do |user| user.provider = auth.provider user.uid = auth.uid user.first_name = auth.info.name user.email = auth.info.email user.password = <PASSWORD>) user.oauth_token = auth.credentials.token user.oauth_expires_at = Time.at(auth.credentials.expires_at) user.save! end end def self.create_user_from_omniauth(auth) puts " ! ! ! ! auth: #{auth.inspect}" create( provider: auth['provider'], uid: auth['uid'], first_name: auth['info']['name'] ) end private # Converts email to all lower-case. def downcase_email self.email = email.downcase end # # Creates and assigns the activation token and digest. # def create_activation_digest # self.activation_token = User.new_token # end end
zivolution921/meobox
config/routes.rb
<reponame>zivolution921/meobox Rails.application.routes.draw do resources :password_resets, only: [:new, :create, :edit, :update] resources :boxes do put 'ship' => 'boxes#ship' end # get 'items/index' # get 'items/new' # get 'items/show' resources :items # get 'history' => 'users#history' resources :plans do resources :boxes do resources :items put 'ship' => 'boxes#ship' end end root 'pages#home' get '/about' => 'pages#about' resources :users do resources :registrations get 'history' => 'users#history' delete 'unsubscribe' => 'registrations#unsubscribe' end get "/sign_in" => "sessions#new", as: :sign_in post "/sign_in" => "sessions#create" # get "/sign_out" => "sessions#destroy", as: :sign_out delete 'sign_out', to: 'sessions#destroy', as: 'sign_out' # named route get "/sign_up" => "users#new", as: :sign_up get 'auth/:provider/callback', to: 'sessions#facebook' # match 'auth/:provider/callback', to: 'sessions#facebook', via: [:get, :post] # match 'auth/failure', to: redirect('/'), via: [:get, :post] resources :charges # API specific routes namespace :api do namespace :v1 do resources :plans resources :users, only: [:index, :create] resources :items resources :boxes end end end
zivolution921/meobox
app/models/box.rb
class Box < ActiveRecord::Base validates :theme_title, :plan_id, presence: true has_many :items belongs_to :plan paginates_per 5 # custom writer, receives array of hash (attributes) for all items def item_attributes=(item_attributes) item_attributes.each do |attributes| items.find_or_create_by(attributes) end end def update_item_attributes=(item_attributes) items.delete_all item_attributes.each do |attributes| items.create(attributes) end end def plan_name plan.name end def shipped? shipped == true end def self.search(search) if search.present? where(["theme_title LIKE ?","%#{search}%"]) else all end end end
zivolution921/meobox
db/migrate/20160629171847_add_columns_for_box.rb
<reponame>zivolution921/meobox<filename>db/migrate/20160629171847_add_columns_for_box.rb<gh_stars>0 class AddColumnsForBox < ActiveRecord::Migration def change remove_column :boxes, :date, :integer add_column :boxes, :theme_title, :string add_column :boxes, :starts_at, :datetime add_column :boxes, :plan_id, :integer end end
zivolution921/meobox
config/initializers/stripe.rb
<reponame>zivolution921/meobox<filename>config/initializers/stripe.rb Rails.configuration.stripe = { :publishable_key => Rails.application.secrets.PUBLISHABLE_KEY, :secret_key => Rails.application.secrets.SECRET_KEY } Stripe.api_key = Rails.application.secrets.SECRET_KEY
zivolution921/meobox
app/models/item.rb
class Item < ActiveRecord::Base belongs_to :box validates :title, :description, :size, presence: true validates :description, length: { minimum: 5 } do_not_validate_attachment_file_type :image has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }, default_url: "/images/missing.jpeg" paginates_per 5 def self.search(search_key_word) if search_key_word.present? && !search_key_word.nil? where(["title LIKE ?","%#{search_key_word}%"]) else all end end end
zivolution921/meobox
config/initializers/omniauth.rb
OmniAuth.config.logger = Rails.logger Rails.application.config.middleware.use OmniAuth::Builder do provider :facebook, '153892268362744 ', 'bf0843ea1f0d7d966c499e4926356d61' end
zivolution921/meobox
app/controllers/boxes_controller.rb
class BoxesController < ApplicationController before_action :set_plan before_action :set_box, except: [:index, :new, :create, :ship] before_action :require_admin, except: [:index, :show] # index action to fetch all the boxes from the database. # boxes for admin do not require a plan def index if @plan @boxes = @plan.boxes.search(params[:search]).page params[:page] else @boxes = Box.search(params[:search]).page params[:page] end end #instantiating box def new @box = Box.new end def create @box = @plan.boxes.new(box_params) puts "inside create box: #{@box.inspect}" if @box.save # array of items attributes # each hash is for one item attributes # so i get 3 hash for 3 items # so its a array of 3 hashes item_attrs = params[:box][:item_attributes].values # using custom attribute writer to create items for the box # we are passing array of hash # @box.item_attributes=(item_attrs) @box.item_attributes = item_attrs redirect_to plan_boxes_path(@plan), notice: 'successfully created ' else render 'new' end end def ship @box = Box.find(params[:box_id]) @box.update_attributes(shipped: true) redirect_to @box, notice: 'successfully shipped!' # redirect_to "/boxes/#{@box.id}" end def show end def edit end def update if @box.update_attributes(box_params) item_attrs = params[:box][:item_attributes].values @box.update_item_attributes = item_attrs redirect_to plan_boxes_path(@plan), notice: 'successfully updated ' else render 'edit' end end def destroy @box.destroy redirect_to boxes_path, notice: 'successfully destroyed' end private def set_item @item = Item.find(params[:item_id]) end def set_plan if params[:plan_id].present? @plan = Plan.find(params[:plan_id]) elsif params[:box].present? && params[:box][:plan_id].present? @plan = Plan.find(params[:box][:plan_id]) end end def set_box # find the box from the database using the id @box = Box.find(params[:id]) end def box_params params.require(:box).permit(:starts_at, :theme_title, :plan_id) end end
zivolution921/meobox
app/serializers/api/v1/box_serializer.rb
class Api::V1::BoxSerializer < ActiveModel::Serializer # attributes that want to return as JSON attributes :plan_name, :title, :theme_title, :shipped has_many :items, serializer: Api::V1::ItemSerializer end
zivolution921/meobox
app/controllers/api/v1/users_controller.rb
class Api::V1::UsersController < ApplicationController # skip to make sure the request came from the correct user and it is safe skip_before_filter :verify_authenticity_token def index users = User.all render json: users, status: :ok end def show user = User.find(params[:id]) render json: user, status: :ok end def new user = User.new end def create user = User.new user_params if user.save render json: { user: user }, status: 201 else errors = user.errors.full_messages render json: {errors: errors}, status: 400 end end private def user_params params.require(:user).permit(:name, :email) end end
zivolution921/meobox
db/migrate/20160629223936_add_shipped_to_box.rb
class AddShippedToBox < ActiveRecord::Migration def change add_column :boxes, :shipped, :boolean, default: false end end
zivolution921/meobox
app/controllers/items_controller.rb
<gh_stars>0 class ItemsController < ApplicationController before_action :set_item, only: [:show, :edit, :update, :destroy] before_action :set_box, except: [:index, :destroy] before_action :set_plan, except: [:index, :show] before_action :require_admin, except: [:index, :show] def index @items = Item.search(params[:search]).page params[:page] end def create @item = @box.items.new(item_params) if @item.save redirect_to items_path, notice: 'successfully created' else render 'new' end end def new @item = Item.new end def show end def edit end def destroy @item.destroy redirect_to items_path, notice: 'successfully deleted ' end private def set_item @item = Item.find(params[:id]) end def set_plan # http://localhost:3000/plans/1/boxes/1/items @plan = if params[:plan_id].present? Plan.find(params[:plan_id]) # non-nested route http://localhost:3000/items/new elsif @box @box.plan end end def set_box # http://localhost:3000/plans/1/boxes/1/items @box = if params[:box_id].present? Box.find(params[:box_id]) # http://localhost:3000/items/new elsif params[:item] && params[:item][:box_id] Box.find(params[:item][:box_id]) end end def item_params params.require(:item).permit(:title, :description, :price, :image, :size, :url, :box_id) end end
zivolution921/meobox
app/controllers/api/v1/items_controller.rb
<gh_stars>0 class Api::V1::ItemsController < ApplicationController def index items = Item.search(params[:search]) # rednering and specifying specific serializer render json: items, root: false, each_serializer: Api::V1::ItemSerializer end def show item = Item.find(params[:id]) render( json: item, root: false, serializer: Api::V1::ItemSerializer ) end def create item = Item.new(item_params) if item.save render json: { item: item }, status: 201 else errors = item.errors.full_messages render json: {errors: errors}, status: 400 end end private def item_params params.require(:item).permit(:title, :description, :price, :image, :size, :url, :box_id) end end
zivolution921/meobox
app/controllers/sessions_controller.rb
<filename>app/controllers/sessions_controller.rb<gh_stars>0 class SessionsController < ApplicationController def new end def create @user = User.find_by_email(params[:email]) # call the authenticate method, # use bcrypt to match the password entered in the sign in form # the password_digest stored in the database if @user && @user.authenticate(params[:password]) session[:user_id] = @user.id # read the value of intended_url in the session hash # if have intended_url will redirect otherwise redirect to user profile redirect_to(session[:intended_url] || @user) session[:intended_url] = nil else render :new end end def facebook user = User.from_omniauth(env["omniauth.auth"]) session[:user_id] = user.id redirect_to root_url, notice: "SIGNED IN" end # delete user_id from session hash def destroy # @user = User.find(params[:id]) # remove user_id key from session session[:user_id] = nil session[:omniauth] = nil redirect_to root_url, alert: "Account successfully deleted!" end end
zivolution921/meobox
app/controllers/api/v1/boxes_controller.rb
<reponame>zivolution921/meobox class Api::V1::BoxesController < ApplicationController def index boxes = Box.all # rednering and specifying specific serializer render json: boxes, root: false, each_serializer: Api::V1::BoxSerializer end def show box = Box.find(params[:id]) render( json: box, root: false, serializer: Api::V1::BoxSerializer ) end def create box = Box.new(box_params) if box.save render json: { box: box }, status: 201 else errors = item.errors.full_messages render json: {errors: errors}, status: 400 end end private def box_params params.require(:box).permit(:starts_at, :theme_title, :plan_id) end end
zivolution921/meobox
app/controllers/api/v1/plans_controller.rb
class Api::V1::PlansController < ApplicationController skip_before_action :verify_authenticity_token def index plans = Plan.all render( root: false, status: :ok, json: plans, each_serializer: Api::V1::PlanSerializer ) end def show plan = Plan.find(params[:id]) render( root: false, status: :ok, json: plan, serializer: Api::V1::PlanSerializer ) end def create plan = Plan.create(plan_params) render( root: false, status: :ok, json: plan, serializer: Api::V1::PlanSerializer ) end def destroy plan = Plan.find(params[:id]) plan.destroy render json: { message: "Successfully deleted the plan" } end private def plan_params params.permit(:user_id, :name, :price, :description, :active) end end
zivolution921/meobox
app/controllers/pages_controller.rb
<filename>app/controllers/pages_controller.rb class PagesController < ApplicationController def home @plan_1 = Plan.find_by_name("Basic Membership") @plan_2 = Plan.find_by_name("Silver Membership") @plan_3 = Plan.find_by_name("Gold Membership") end def about end end
zivolution921/meobox
app/models/registration.rb
<reponame>zivolution921/meobox<filename>app/models/registration.rb<gh_stars>0 class Registration < ActiveRecord::Base belongs_to :plan belongs_to :user validates :plan, :uniqueness => {:scope => :user} end
zivolution921/meobox
app/serializers/api/v1/plan_serializer.rb
class Api::V1::PlanSerializer < ActiveModel::Serializer attributes :name, :description, :price, :active, :user_id has_many :boxes, serializer: Api::V1::BoxSerializer end
zivolution921/meobox
app/serializers/api/v1/item_serializer.rb
<reponame>zivolution921/meobox<filename>app/serializers/api/v1/item_serializer.rb class Api::V1::ItemSerializer < ActiveModel::Serializer attributes :id, :description, :title, :size, :url, :price, :edit_url, :formatted_price # define custom method for the object def edit_url edit_item_url(object) end def formatted_price ActiveSupport::NumberHelper.number_to_currency(object.price) || '$100.00' end end
zivolution921/meobox
app/controllers/registrations_controller.rb
class RegistrationsController < ApplicationController def create @plan = Plan.find_by_name(params[:plan_name]) @user = User.find(params[:user_id]) # attach the plan to the user if @user.already_registered_for_any_plan? flash[:notice] = "You are already subscribed to #{current_user.plan.name}! You have to unsubscribe that plan in order to subscribe a new plan" else flash[:notice] = "Successfully subscribed to #{@plan.name}!" Registration.create(user_id: @user.id, plan_id: @plan.id, expired_at: DateTime.now + 1.month) end redirect_to @plan end def unsubscribe @plan = Plan.find_by_name(params[:plan_name]) @user = User.find(params[:user_id]) # flash[:notice] = "You are unsubscribed to #{@plan.name}!" Registration.where(user_id: @user.id, plan_id: @plan.id).destroy_all redirect_to :root end end
zivolution921/meobox
app/models/plan.rb
<filename>app/models/plan.rb class Plan < ActiveRecord::Base has_many :registrations has_many :users, through: :registrations has_many :boxes validates_presence_of :name, :description, :price validates :price, numericality: { greater_than: 0 } def rounded_price self.price.round end end
zivolution921/meobox
db/migrate/20160625152638_remove_columns_from_registration.rb
class RemoveColumnsFromRegistration < ActiveRecord::Migration def change remove_column :registrations, :name, :string remove_column :registrations, :email, :string end end
zivolution921/meobox
app/controllers/application_controller.rb
<filename>app/controllers/application_controller.rb class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # Cross Site Forgery request # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception include CanCan::ControllerAdditions # create an instance variable that if a session variable "user_id" exists, # will return the correspond user and assign it to the that variable. private def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end helper_method :current_user def current_user?(user) current_user == user end helper_method :current_user? def current_user_admin? current_user && current_user.admin? end helper_method :current_user_admin? def require_admin unless current_user_admin? redirect_to root_url, alert: "Unauthorized access!" end end # store intended_url in the session # assign value to session with url requested under the key intended_url def require_signin unless current_user session[:intended_url] = request.url redirect_to new_user_path, alert: "Please sign in first!" end end helper_method :require_signin end
zivolution921/meobox
test/controllers/plans_controller_test.rb
<gh_stars>0 require 'test_helper' class PlansControllerTest < ActionController::TestCase setup do @plan = plans(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:plans) end test "should get new" do get :new assert_response :success end test "should create plan" do assert_difference('Plan.count') do post :create, plan: { } end assert_redirected_to plan_path(assigns(:plan)) end test "should show plan" do get :show, id: @plan assert_response :success end test "should get edit" do get :edit, id: @plan assert_response :success end test "should update plan" do patch :update, id: @plan, plan: { } assert_redirected_to plan_path(assigns(:plan)) end test "should destroy plan" do assert_difference('Plan.count', -1) do delete :destroy, id: @plan end assert_redirected_to plans_path end end
zivolution921/meobox
db/migrate/20160627202826_change_uid_limit_of_user.rb
<reponame>zivolution921/meobox<gh_stars>0 class ChangeUidLimitOfUser < ActiveRecord::Migration def change remove_column :users, :uid, :intger add_column :users, :uid, :text end end
zivolution921/meobox
app/serializers/api/v1/user_serializer.rb
<filename>app/serializers/api/v1/user_serializer.rb class Api::V1::UserSerializer < ActiveModel::Serializer attributes :first_name, :last_name, :email, :password, :password_confirmation, :avatar end
skoba/fhir-ruby
spec/spec_helper.rb
<reponame>skoba/fhir-ruby require 'fhir' require 'open-uri' FHIR_URI = 'http://www.hl7.org/implement/standards/fhir/profiles-resources.xml' FHIR_FILE = "#{File.dirname(__FILE__)}/tmp/cache.xml" unless File.exists?(FHIR_FILE) f = open(FHIR_URI) FileUtils.mkdir_p(File.dirname(FHIR_FILE)) File.open(FHIR_FILE, 'w') do |cf| cf << f.readlines.join("\n") end end DATATYPES_FILE = File.join(File.dirname(__FILE__), '..', 'fhir-base.xsd') Fhir.configure do |cfg| cfg.selection_modules = [] cfg.node_modules = [] cfg.fhir_xml = FHIR_FILE cfg.datatypes_xsd = DATATYPES_FILE end
skoba/fhir-ruby
lib/fhir/resource.rb
require 'nokogiri' module Fhir #Follow xml definition structure class Resource < Fhir::ActiveXml class Element < Fhir::ActiveXml def path value_from_path('path').split('.') end def definition @definition ||= Definition.new(node.xpath('./definition').first) end def name path.last end class Definition < Fhir::ActiveXml value_attr 'max' value_attr 'min' value_attr 'short' value_attr 'formal' value_attr 'comments' value_attr './type/code', 'type' end end class << self attr :source def load(path) @source = Nokogiri::XML(open(path).readlines.join("")) @source.remove_namespaces! end def all resources end def find(name) resources.find{|r| r.name == name } end def resources @resources ||= source.xpath('//Profile/structure').map{|n| self.new(n)} end end value_attr 'type', 'name' value_attr 'type' def elements @elements ||= node .xpath('./element') .map{|n| Element.new(n) } end end end
skoba/fhir-ruby
spec/node_functions_spec.rb
require 'spec_helper' describe 'NodeFunctions' do let(:graph) do Fhir::Graph.new.tap do |g| g.add([1]) g.add([1, 2]) g.add([1, 2, 3]) g.add([1, 2, 3, 4]) g.add([1, 2, 3, 4, 5]) g.add([1, 6]) end end let(:selection) { graph.selection } let(:node) { selection.select { |n| n.path.to_a == [1, 2, 3] }.to_a.first } it 'should get children' do node.children.to_a.map(&:path).map(&:to_a).should =~ [[1, 2, 3, 4]] end it 'should get parents' do node.parent.path.to_a.should == [1, 2] end it 'should get ancestors' do node.ancestors.to_a.map(&:path).map(&:to_a).should =~ [[1], [1, 2]] end it 'should get descendants' do node.descendants.to_a.map(&:path).map(&:to_a).should =~ [[1, 2, 3, 4], [1, 2, 3, 4, 5]] end end
skoba/fhir-ruby
example_project/gen/expand_graph.rb
<filename>example_project/gen/expand_graph.rb class ExpandGraph def initialize(graph) @graph = graph end def expand @graph.selection.by_attr(:embed, true).each do |node| res = node.referenced_resource res.descendants.each do |dsc| path = node.path.to_a + dsc.path.to_a[1..-1] @graph.add(path, dsc.attributes.dup) unless @graph.path_exists?(path) end end end end
skoba/fhir-ruby
lib/fhir/node_functions.rb
<reponame>skoba/fhir-ruby<gh_stars>1-10 module Fhir module NodeFunctions def children(node, selection) selection.select do |n| node.path.child?(n) end end def parent(node, selection) selection.to_a.find do |n| n.path.child?(node) end end def ancestors(node, selection) selection.select do |n| n.path > node.path end end def descendants(node, selection) selection.select do |n| n.path < node.path end end end end
skoba/fhir-ruby
example_project/spec/condition_spec.rb
<reponame>skoba/fhir-ruby<gh_stars>1-10 require 'spec_helper' describe 'Condition' do example do codeable_concept_attributes = { text: 'code text' } date = Time.now evidence_attrs = {code_attributes: codeable_concept_attributes} location_attrs = {detail: 'detail', code_attributes: codeable_concept_attributes} related_item_attrs = {type_name: 'follows', code_attributes: codeable_concept_attributes} condition = Fhir::Condition.create!( date_asserted: date, asserter_attributes: { name_attributes: { text: 'Roman', family: ['Abramovich', 'Yanukovich'], given: ['Albert', 'Eduard']} }, code_attributes: codeable_concept_attributes, category_attributes: codeable_concept_attributes, status: 'working', certainty_attributes: codeable_concept_attributes, severity_attributes: codeable_concept_attributes, onset: date, # abatement: false, stage_attributes: { summary_attributes: codeable_concept_attributes }, notes: 'notes', evidences_attributes: [evidence_attrs], locations_attributes: [location_attrs], related_items_attributes: [related_item_attrs] ) condition.save! condition.reload condition.date_asserted.should be_a(Date) condition.code.text.should == 'code text' condition.category.text.should == 'code text' condition.status.should == 'working' condition.certainty.text.should == 'code text' condition.severity.text.should == 'code text' condition.onset.should be_a(Date) # condition.abatement.should be_false condition.stage.summary.text.should == 'code text' condition.notes.should == 'notes' condition.evidences.first.code.text.should == 'code text' condition.locations.first.code.text.should == 'code text' condition.locations.first.detail.should == 'detail' p condition.related_items condition.related_items.first.code.text.should == 'code text' condition.related_items.first.type_name.should == 'follows' end end
skoba/fhir-ruby
example_project/gen/rules.rb
class Rules def self.apply(graph) graph.rule(%w[MedicationStatement dosage site coding], max: '1') graph.rule(%w[MedicationStatement dosage route coding], max: '1') graph.rule(%w[MedicationStatement dosage method coding], max: '1') graph.rule(%w[MedicationStatement identifier], max: '1') graph.rule(%w[MedicationStatement reasonNotGiven coding], max: '1') graph.rule(%w[MedicationStatement medication], max: '1', embed: true) graph.rule(%w[MedicationStatement medication package], max: '0') graph.rule(%w[MedicationStatement medication product], max: '0') graph.rule(%w[AllergyIntolerance recorder], type: 'Resource(Practitioner)', embed: true) graph.rule(%w[AllergyIntolerance substance], embed: true) graph.rule(%w[AllergyIntolerance reaction], embed: true) graph.rule(%w[Condition asserter], type: 'Resource(Practitioner)', embed: true) end end
skoba/fhir-ruby
lib/fhir/graph.rb
module Fhir class Graph attr :modules attr :node_modules def initialize(options = {}) @index = {} @options = options @modules = Array(options[:modules]) @node_modules = Array(options[:node_modules]) end def nodes @nodes ||= [] end def path_exists?(path) @index.key?(path.to_s) end def add(path, attrs = {}) raise "Duplicate node #{path} in graph" if @index.key?(path.to_s) @index[path.to_s] = true node = Node.new(self, path, attrs) nodes<< node node end def rule(path_expression, attrs = {}) nodes.each do |node| if node.path == Fhir::Path.new(path_expression) node.attributes.merge!(attrs) end end end def selection Selection.new(self, nodes) end end end
skoba/fhir-ruby
lib/fhir/datatype.rb
<gh_stars>1-10 require 'nokogiri' module Fhir class Datatype class << self def load(path) @document = Nokogiri::XML(open(path).readlines.join("")) @document.remove_namespaces! end def all types end def find(name) types.select do |type| type.name == name end.first end def enum_values(type_name) enum_type = @document.xpath("//schema/simpleType[@name='#{type_name}']") enum_type.xpath('./restriction/enumeration').map { |node| node[:value] } end private def types @types ||= parse_types end def parse_types @document.xpath('//schema/complexType').map do |complex_type| self.new(complex_type) end end end SIMPLE_TYPES = %w[decimal integer boolean instant date base64Binary string uri dateTime id code oid uuid Element] def initialize(node) @node = node end def name @name ||= @node[:name] end def simple? return @simple unless @simple.nil? @simple = SIMPLE_TYPES.include?(name) || enum? end def complex? ! simple? end def enum? return @enum unless @enum.nil? @node.xpath('./complexContent/extension/attribute').tap do |nodes| @enum = (nodes.size == 1 && !!(nodes.first[:type] =~ /-list$/)) end @enum end def annotation @node.xpath('./annotation/documentation').map(&:text).join("\n") end def attributes return nil if simple? @attributes ||= parse_attributes end def enum_values return nil unless enum? simple_type = @node.xpath('./complexContent/extension/attribute').first[:type] self.class.enum_values(simple_type) end private class Attribute attr_accessor :name, :type, :type_name, :min, :max def initialize(attribute) @name = attribute[:name] || attribute[:ref] @type_name = attribute[:type] || attribute[:ref] @type = Datatype.find(attribute[:type]) @min = attribute[:minOccurs] @max = attribute[:maxOccurs] end end def parse_attributes attributes = [] @node.xpath('./complexContent/extension/sequence/element').each do |attribute| attributes << Attribute.new(attribute) end attributes end end end
skoba/fhir-ruby
example_project/gen/node_functions.rb
<gh_stars>1-10 module NodeFunctions def class_name(node, _) node.path.to_a.map(&:camelize).join end def table_name(node, _) node.path.to_a.map(&:underscore).join('_').tableize end def class_file_name(node, _) node.class_name.underscore end def references(node, selection) node.children .reject_contained .resource_refs .by_attr(:embed, nil) end def belongs_to(node, selection) node.ancestors.to_a.sort_by { |n| n.path.length }.reverse.find do |n| n.max == '*' or n.type == 'Resource' end end def resource_ref?(node, _) node.path.size > 1 && node.type =~ /^Resource/ && !node.attributes[:embed] end def has_identity?(node, _) node.children.to_a.any? do |child| child.name == 'identifier' end end def embedded_associations(node, selection) node .children .by_attr('max', '*') .reject_contained .complex end def associations(node, selection) nodes = node .children .by_attr('max', '*') .reject_contained .complex nodes + node .children .select{|n| n.max != '0'} .map(&:associations) .flatten end def embedded_objects(node, _) node .children .by_attr('max', '1') .reject_contained .complex end def embedded_descendants(node, _) node.embedded_objects + (node.embedded_objects + node.embedded_associations) .map(&:embedded_descendants).flatten end def resource_name(node, _) node.type.gsub(/^Resource\(/, '').gsub(/\)/, '') end def referenced_resource(node, selection) selection.node([node.resource_name]) end def columns(node, selection) singular = node.children.by_attr('max', '1') singular.simple.simple_types.reject_idrefs + singular.map(&:columns).flatten end def serializable_attributes(node, _) node.children.simple.by_attr('max', '*') end def all_serializable_attributes(node, _) node.serializable_attributes + node.children .by_attr('max', '1') .map(&:all_serializable_attributes) .flatten end def model_attributes(node, selection) node.children.by_attr('max', '1').simple.simple_types.reject_idrefs end def embedded_children(node, selection) node.children.complex.by_attr('max', '1') end def column_name(node, _, parent) postfix = { 'system' => '_name', 'type' => '_name' }[node.name] || '' (node.path - parent.path) .to_a.map(&:underscore) .join('__').gsub('[x]','') + postfix end def column_type(node, _) { 'decimal' => 'decimal', 'integer' => 'integer', 'boolean' => 'boolean', 'instant' => 'string', 'date' => 'date', 'base64Binary' => 'bytea', 'string' => 'string', 'uri' => 'string', 'dateTime' => 'datetime', 'id' => 'integer', 'code' => 'string', 'oid' => 'string', 'uuid' => 'string' }[node.type] || node.type end end
skoba/fhir-ruby
lib/fhir/template_functions.rb
module Fhir module TemplateFunctions def template(selection, opts = {}, &block) opts = {attr_to_write: :template_result}.merge(opts) path = opts[:path] template_str = block_given? ? block.call : File.read(path) template = ERB.new(template_str, nil, '%<>-') template.filename = path if path selection.select do |node| node.attributes[opts[:attr_to_write]] = template.result(binding) end end def render(selection, indent = 0, attr_to_read = :template_result) spaces = ' '*indent selection .to_a .map { |e| e.attributes[attr_to_read].gsub(/^(.+)$/, "#{spaces}\\1") } .join("\n") end def file(selection, folder_path, attr_to_read = :template_result, &block) FileUtils.mkdir_p(folder_path) selection.to_a.each do |node| content = node.attributes[attr_to_read] file_name = block.call(node) File.open(File.join(folder_path, file_name), 'w') { |f| f<< content } end selection end end end
skoba/fhir-ruby
example_project/spec/spec_helper.rb
<filename>example_project/spec/spec_helper.rb system "bundle exec ../bin/fhir Fhirfile" unless ENV['NOGEN'] require 'active_support' require 'active_record' require 'active_support/core_ext' require 'active_support/dependencies' ::FHIR_PATH = File.expand_path(File.dirname(__FILE__)) $:.unshift(File.expand_path('../../lib', FHIR_PATH)) #include fhir require 'fhir' %w[models lib gen].each do |folder| ActiveSupport::Dependencies.autoload_paths << "#{FHIR_PATH}/../#{folder}" end Fhir.configure do |cfg| cfg.fhir_xml = FHIR_PATH + '/../../spec/tmp/cache.xml' cfg.datatypes_xsd = FHIR_PATH + '/../../fhir-base.xsd' cfg.node_modules = [NodeFunctions] cfg.selection_modules = [SelectionFunctions] end Rules.apply(Fhir.graph) ExpandGraph.new(Fhir.graph).expand FHIR_SPEC_ROOT = File.dirname(__FILE__) ActiveRecord::Base.establish_connection(YAML.load_file( FHIR_SPEC_ROOT + '/database.yml')) unless ENV['NOGEN'] ActiveRecord::Schema.define do eval File.read(File.dirname(__FILE__) + '/../migrations/schema.rb') end end
skoba/fhir-ruby
example_project/spec/node_functions_spec.rb
require 'spec_helper' describe NodeFunctions do let(:selection) { Fhir.graph.selection } let(:condition) { selection.node(['Condition']) } let(:medstatement) { selection.node(['MedicationStatement']) } let(:medication) { selection.node(['Medication']) } let(:dose) { selection.node(['MedicationStatement','dosage']) } let(:route) { selection.node(['MedicationStatement','dosage', 'route']) } let(:medstatement_patient) { selection.node(['MedicationStatement', 'patient']) } let(:patient) { selection.node(['Patient']) } let(:when_given_start) { selection.node(['MedicationStatement', 'whenGiven', 'start']) } example 'class_name' do medstatement.class_name.should == 'MedicationStatement' dose.class_name.should == 'MedicationStatementDosage' route.class_name.should == 'MedicationStatementDosageRoute' end example 'belongs_to' do selection .node(['MedicationStatement', 'medication', 'code', 'coding']) .belongs_to end example 'table_name' do medstatement.table_name.should == 'medication_statements' dose.table_name.should == 'medication_statement_dosages' route.table_name.should == 'medication_statement_dosage_routes' end example 'class_file_name' do route.class_file_name.should == 'medication_statement_dosage_route' end example 'references' do medstatement .references .to_a .map(&:name) .should =~ ["administrationDevice", "patient"] end example 'embedded_associations' do medstatement .embedded_associations .to_a .map(&:name) .should =~ %w[dosage reasonNotGiven] end example 'associations' do medstatement .associations .to_a .map(&:table_name).should =~ ["medication_statement_dosage_timing_events", "medication_statement_dosages", "medication_statement_medication_code_codings", "medication_statement_medication_package_container_codings", "medication_statement_medication_package_contents", "medication_statement_medication_product_form_codings", "medication_statement_medication_product_ingredients", "medication_statement_reason_not_givens"] end example 'resource name' do medstatement_patient.resource_name.should == 'Patient' end example 'referenced resource' do medstatement_patient.referenced_resource.should == patient end example 'columns serializable attributes' do condition .all_serializable_attributes .to_a .map{|n| n.column_name(condition) } .should include("asserter__name__given") end example 'columns' do medstatement .columns .to_a .map{|n| n.column_name(medstatement)} .should =~ ["identifier__assigner__display", "identifier__assigner__reference", "identifier__assigner__type_name", "identifier__key", "identifier__label", "identifier__period__end", "identifier__period__start", "identifier__system_name", "language", "was_not_given", "when_given__end", "when_given__start", "medication__code__text", "medication__is_brand", "medication__kind", "medication__language", "medication__name", "medication__package__container__text", "medication__product__form__text"] end example 'model attributes' do medstatement .model_attributes .to_a .map(&:name) .should =~ %w[language wasNotGiven] end example 'embedded children' do medstatement .embedded_children .to_a .map(&:name) .should =~ %w[whenGiven identifier medication] end example 'column name' do when_given_start.column_name(medstatement).should == 'when_given__start' end example 'resource_ref?' do medication.resource_ref?.should be_false medstatement_patient.resource_ref?.should be_true end example 'has_identity?' do medication.has_identity?.should be_false medstatement.has_identity?.should be_true end end
skoba/fhir-ruby
lib/fhir/path.rb
<filename>lib/fhir/path.rb module Fhir class Path include Comparable def initialize(path) @array = uniform(path).freeze end def inspect to_a.join('.') end def to_a @array end def to_s to_a.join('.') end def subpath?(subpath) subpath = uniform(subpath) self_or_subpath?(subpath) && subpath.size > self.size end def child?(subpath) to_a == uniform(subpath)[0...-1] end alias :include? :subpath? def self_or_subpath?(subpath) uniform(subpath).to_a[0...self.to_a.length] == self.to_a end def [](range_or_index) if range_or_index.is_a?(Range) self.class.new(to_a[range_or_index]) else to_a[range_or_index] end end def >=(subpath) self_or_subpath?(subpath) end def <=(superpath) superpath.self_or_subpath?(self) end def >(subpath) subpath?(subpath) end def <(superpath) superpath.subpath?(self) end def length to_a.length end def last to_a.last end def first to_a.last end alias :size :length def relative(path) raise "#{path} not subpath of #{self}" unless path.subpath?(self) self.class.new(to_a[path.length..-1]) end def -(path) relative(path) end def concat(other_path) self.class.new(to_a + other_path.to_a) end def join(*args) concat(args) end def +(other_path) concat(other_path) end def ==(other_path) to_a == other_path.to_a end def <=>(other) to_a <=> other.to_a end def initialize_copy(origin) @array = origin.to_a end alias :eql? :== private def uniform(object) case object when Fhir::Node object.path.to_a when Fhir::Path object.to_a when Array object else raise "Not valid path #{object}" end end end end
skoba/fhir-ruby
lib/fhir/active_xml.rb
module Fhir class ActiveXml attr :node def initialize(node) @node = node end def self.value_attr(path, name = nil) name ||= path.split('/').last self.send :define_method, name do value_from_path(path) end end def value_from_path(path) (node.xpath("./#{path}").first || {})[:value] end end end
skoba/fhir-ruby
lib/fhir/node.rb
<gh_stars>1-10 module Fhir class Node attr :graph attr :path attr :attributes def initialize(graph, path, attrs) @graph, @path, @attributes = graph, Fhir::Path.new(path), attrs end def name path.last end def max attributes[:max] || '1' end def min attributes[:min] || '0' end def type attributes[:type] || '' end def comment attributes[:comment] || '' end def inspect "<Node:#{@path.inspect}(#{attributes.inspect})>" end def respond_to_missing?(meth, *args) mod.respond_to?(meth) end def method_missing(name, *args, &block) if mod.respond_to?(name) mod.send(name, self, graph.selection, *args, &block) else super end end private def mod @mod ||= Module.new.tap do |mod| mod.send(:extend, NodeFunctions) @graph.node_modules.each {|m| mod.send(:extend, m) } end end end end
skoba/fhir-ruby
spec/node_spec.rb
require 'spec_helper' describe 'Fhir::Node' do module NodeRole def children(node, selection, *args) node end end example do graph = Object.new graph.stub(:node_modules).and_return([NodeRole]) graph.stub(:selection).and_return([NodeRole]) node = Fhir::Node.new(graph, ['a','b'], prop: 'val') node.name.should == 'b' node.path.should be_a(Fhir::Path) node.should respond_to(:children) node.children.should == node end end
skoba/fhir-ruby
lib/fhir.rb
$:.unshift(File.expand_path(File.dirname(__FILE__))) unless $:.include?(File.dirname(__FILE__)) require 'ostruct' require 'active_support/core_ext' module Fhir autoload :Cli, 'fhir/cli' autoload :Resource, 'fhir/resource' autoload :ActiveXml, 'fhir/active_xml' autoload :Datatype, 'fhir/datatype' autoload :Path, 'fhir/path' autoload :Graph, 'fhir/graph' autoload :Selection, 'fhir/selection' autoload :Node, 'fhir/node' autoload :TemplateFunctions, 'fhir/template_functions' autoload :SelecionFunctions, 'fhir/selection_functions' autoload :NodeFunctions, 'fhir/node_functions' def self.configure(&block) @config = OpenStruct.new block.call(@config) end def self.graph modules = @config.selection_modules node_modules = @config.node_modules @graph ||= Graph.new(modules: modules, node_modules: node_modules).tap do |g| Fhir::Resource.load(@config.fhir_xml) Fhir::Datatype.load(@config.datatypes_xsd) Resource.all.each do |r| r.elements.each do |el| expand_datatypes g, g.add(el.path, comment: el.definition.short, max: el.definition.max, min: el.definition.min, from: :fhir, type: el.definition.type) end end end end def self.expand_datatypes(graph, nodes) Array(nodes).map do |parent| type = Datatype.find(parent.type) next unless type next if %w[Extension Narrative].include?(type.name) next unless type.complex? next if type.attributes.empty? create_nodes_from_datatype_attrs(graph, parent, type.attributes) end end def self.create_nodes_from_datatype_attrs(graph, parent, attrs) attrs.map do |attr| # return [] unless node.path.size > 1 node = graph.add(parent.path.join(attr.name), type: attr.type_name, max: attr.max == 'unbounded' ? '*' : attr.max, min: attr.min, simple: attr.type.try(:simple?), comment: attr.type.try(:annotation), from: :datatypes, datatype_attr: true) expand_datatypes(graph, node) end end def self.generate(&block) block.call(graph) end end
skoba/fhir-ruby
example_project/lib/fhir/composite.rb
<gh_stars>1-10 # Composite, allow object to compose group of attributes prefixed with composing name: <composing>__<attr_name> # Similar to http://apidock.com/rails/ActiveRecord/Aggregations/ClassMethods/composed_of module Fhir::Composite extend ActiveSupport::Concern module ClassMethods def composing(composing_name, opts = {}) class_name = opts.fetch(:class_name) line = __LINE__ class_eval <<-RUBY, __FILE__, line + 2 def build_#{composing_name}(attrs = {}) # def build_address(attrs = {}) @_#{composing_name} = nil # @_address = nil self.#{composing_name}_attributes = attrs # self.address_attributes = attrs @_#{composing_name} # @_address end # end #TODO: entry-point to initialize attribute names by convention def _#{composing_name} # def _address @_#{composing_name} ||= begin # @_address ||= begin init_attrs = {composite: self, composing_name: '#{composing_name}'} # init_attrs = {composite: self, composing_name: 'address'} #{class_name}.new(init_attrs) # Address.new(init_attrs) end # end end # end def #{composing_name} # def address _#{composing_name}.presence # _address.presence end # end def #{composing_name}_attributes=(attrs = {}) # def address_attributes(attrs = {}) attrs.each do |name, value| # attrs.each do |name, value| _#{composing_name}.send("\#{name}=", value) # _address.send("\#{name}=", value) end # end end # end RUBY end end end
skoba/fhir-ruby
example_project/lib/fhir/composing.rb
# Part of composite # Allow to use model as part of another object delegating attribute accessors by convention: <composing>__<attr_name> module Fhir::Composing extend ActiveSupport::Concern attr_accessor :composite, :composing_name def initialize(attrs = {}) composite = attrs.fetch(:composite) composing_name = attrs.fetch(:composing_name) if composite.respond_to?(:composing_name) self.composite = composite.composite self.composing_name = [composite.composing_name, composing_name].join('__') else self.composite, self.composing_name = composite, composing_name end self.attributes = attrs.except(:composite, :composing_name) end def attributes composing_attribute_names.each_with_object({}) do |attr_name, attrs| attrs[attr_name] = send(attr_name) end end def attributes=(attrs) attrs.each do |key, value| self.send("#{key}=", value) end end def blank? attributes.values.all?(&:blank?) end included do class_attribute :composing_attribute_names self.composing_attribute_names = [] end private def read_composing_attribute(attr_name) reader_method_name = "#{composing_name}__#{attr_name}" composite.send(reader_method_name) if composite.respond_to?(reader_method_name) end def write_composing_attribute(attr_name, val) composite.send("#{composing_name}__#{attr_name}=", val) end module ClassMethods def composing_attribute(*attribute_names) self.composing_attribute_names += attribute_names attribute_names.each do |attr_name| self.send(:define_method, attr_name) do read_composing_attribute(attr_name) end self.send(:define_method, "#{attr_name}=") do |val| write_composing_attribute(attr_name, val) end end end end end
skoba/fhir-ruby
example_project/lib/fhir/migration_helpers.rb
module Fhir module MigrationHelpers def identifier_table(entity_name) create_table("certification_#{entity_name}_identifiers") do |t| t.integer "#{entity_name}_id" t.string :use # enum t.string :label t.string :system_name t.string :key t.string :assigner_id #references organization end end def coding_fields(t, *path) prefix = path.present? ? "#{path.join('__')}__" : '' t.string "#{prefix}system_name" t.string "#{prefix}code" t.string "#{prefix}display" end def period_fields(t, *path) prefix = path.present? ? "#{path.join('__')}__" : '' t.string "#{prefix}start_datetime" t.string "#{prefix}end_datetime" end def quantity_fields(t, *path) prefix = path.present? ? "#{path.join('__')}__" : '' t.decimal "#{prefix}value" t.string "#{prefix}comparator" #code t.string "#{prefix}units" t.string "#{prefix}system_name" #uri t.string "#{prefix}code" #code end def ratio_fields(t, *path) quantity_fields t, *(path + [:numerator]) quantity_fields t, *(path + [:denominator]) end end end
skoba/fhir-ruby
spec/selection_functions_spec.rb
<reponame>skoba/fhir-ruby<gh_stars>1-10 require 'spec_helper' describe Fhir::SelecionFunctions do let(:graph) do Fhir::Graph.new.tap do |g| g.add([1]) g.add([1, 2]) g.add([1, 2, 3]) g.add([1, 4]) end end let(:selection) { graph.selection } it 'should debug' do selection.should respond_to(:debug) end it 'should select' do nodes = selection.select do |node| node.path.to_a.include?(2) end nodes.to_a.size.should == 2 end it 'should select branch' do selection.branch([1,4]).to_a.size.should == 1 selection.branch([1,2]).to_a.size.should == 2 selection.branch([1]).to_a.size.should == 4 end it 'should select branches' do selection.branches([1,4], [1,2,3]) .to_a .map(&:path) .map(&:to_a) .should == [[1,4],[1,2,3]] end end
skoba/fhir-ruby
lib/fhir/selection_functions.rb
module Fhir module SelecionFunctions def debug(selection, title = nil, attr = nil) puts puts "DEBUG: #{title}" if title puts '-'*20 puts "\n " + selection.to_a.map(&(attr || :inspect)).join("\n ") selection end def select(selection, &block) selection.selection(selection.to_a.select(&block)) end def branch(selection, path, &block) selection.select do |node| node.path <= Fhir::Path.new(path) end end def branches(selection, *paths, &block) paths.map do |path| selection.branch(path) end.sum end def children(selection) selection.map(&:children).flatten end def simple(selection) selection.select do |node| node.children.to_a.empty? && node.type !~ /^Resource/ end end def complex(selection) selection.select do |node| not node.children.to_a.empty? end end def by_attr(selection, name, val) selection.select do |node| if node.respond_to?(name) node.send(name) == val else node.attributes[name] == val end end end def parents(selection) selection.map(&:parent) end def node(selection, path) selection.to_a.find do |node| node.path == Fhir::Path.new(path) end end end end
skoba/fhir-ruby
example_project/spec/medication_statement_spec.rb
<filename>example_project/spec/medication_statement_spec.rb require 'spec_helper' describe 'Medication Statement' do example do codings_attributes = [ { system_name: 'rxnorm.info', code: '312961' }, { system_name: 'ndc', code: '52959-989' } ] medication_attributes = { name: 'Simvastatin 20 mg tablet', code_attributes: { text: 'Simvastatin 20 mg tablet', codings_attributes: codings_attributes } } identifier_attributes = { key: '321312', assigner_attributes: { type_name: 'hospital rx', display: 'Apteka' } } dosages_attributes = [ { route_attributes: { coding_attributes: { system_name: 'snomed', code: '3123213', display: 'Oral' } } } ] statement = Fhir::MedicationStatement.create( medication_attributes: medication_attributes, identifier_attributes: identifier_attributes, dosages_attributes: dosages_attributes ) statement.medication.name.should == 'Simvastatin 20 mg tablet' statement.medication.code.text.should == 'Simvastatin 20 mg tablet' coding = statement.medication.code.codings coding.should have(2).items coding.to_a.find { |c| c.system_name == 'rxnorm.info' }.code.should == '312961' coding.to_a.find { |c| c.system_name == 'ndc' }.code.should == '52959-989' statement.dosages.first.route.coding.display.should == 'Oral' end end
skoba/fhir-ruby
example_project/spec/selection_functions_spec.rb
require 'spec_helper' describe SelectionFunctions do let(:selection) { Fhir.graph.selection } it "#value objects" do selection .branch(['MedicationStatement']) .value_objects end it 'should select tables' do selection .branch(['AllergyIntolerance']) .tables .to_a .map(&:table_name) .size.should == 21 end end
skoba/fhir-ruby
example_project/lib/fhir/base.rb
<reponame>skoba/fhir-ruby<filename>example_project/lib/fhir/base.rb class Fhir::Base < ActiveRecord::Base self.table_name_prefix = 'fhir.' self.abstract_class = true end
skoba/fhir-ruby
spec/datatype_spec.rb
require 'spec_helper' describe Fhir::Datatype do before :all do Fhir::Datatype.load(DATATYPES_FILE) end it 'should detect simple types' do Fhir::Datatype.find('integer').should be_simple Fhir::Datatype.find('id').should be_simple Fhir::Datatype.find('Element').should be_simple Fhir::Datatype.find('QuantityCompararator').should be_simple Fhir::Datatype.find('Extension').should be_complex Fhir::Datatype.find('Address').should be_complex end it 'should parse attributes' do Fhir::Datatype.all.each do |datatype| puts datatype.name if datatype.complex? datatype.attributes.each do |attribute| attribute.type.should be_a Fhir::Datatype if attribute.type puts " #{attribute.name} <#{attribute.type_name}> #{attribute.min}..#{attribute.max}" end elsif datatype.simple? datatype.attributes.should be_nil end puts end end it 'should detect and parse enum' do Fhir::Datatype.find('Address').should_not be_enum datatype = Fhir::Datatype.find('ObservationStatus') datatype.should be_enum datatype.enum_values.should =~ %w[registered interim final amended cancelled withdrawn] end it 'should do something' do file_name = File.join(File.dirname(__FILE__), '..', 'fhir-base.xsd') document = Nokogiri::XML(File.open(file_name).readlines.join) document.remove_namespaces! complex_types = document.xpath('//schema/complexType') ext_contents = [] complex_types.each do |type| puts type[:name] type.xpath('./attribute').each do |attribute| puts " A #{attribute[:name]} <#{attribute[:type]}>" end type.xpath('./choice').each do |choice| puts " CH #{choice[:minOccurs]}..#{choice[:maxOccurs]}" choice.xpath('./element').each do |element| puts " E #{element[:ref]}" end end type.xpath('./sequence/choice').each do |choice| puts " S CH #{choice[:minOccurs]}..#{choice[:maxOccurs]}" choice.xpath('./element').each do |element| puts " E #{element[:name]} <#{element[:type]}>" end end type.xpath('./sequence/element').each do |element| puts " S E #{element[:name]} <#{element[:type]}>" end type.xpath('./resctirction/enumaeration').each do |enumeration| puts " R EN #{enumeration[:value]}" end type.xpath('./complexContent/extension/attribute').each do |attribute| puts " CO EXT A #{attribute[:name]} <#{attribute[:type]}>" end type.xpath('./complexContent/extension/sequence/element').each do |element| puts " CO EXT S E #{element[:name]} <#{element[:type]}>" end type.xpath('./complexContent/restriction/sequence/element').each do |element| puts " CO R S E #{element[:name]} <#{element[:type]}>" end puts end end end
skoba/fhir-ruby
example_project/spec/allergy_intolerance_spec.rb
<reponame>skoba/fhir-ruby require 'spec_helper' describe 'AllergyIntolerance' do example do allergy = Fhir::AllergyIntolerance.create!( criticality: 'fatal', sensitivity_type: 'allergy', recorded_date: Time.now, status: 'status', substance_attributes: { name: 'substance name', type_attributes: { text: 'aspirin', codings_attributes: [{system_name: 'RxNorm', code: '123456', display: 'aspirin'}] }, description: 'substance description', status_attributes: { text: 'active' }, effective_time_attributes: { start: Time.now, end: Time.now } }, reactions_attributes: [{ reaction_date: Time.now, did_not_occur_flag: false, symptoms_attributes: [{ code_attributes: {text: 'pain'}, severity: 'over 9000' }], exposures_attributes: [{ exposure_date: Time.now, exposure_type: 'exposure type', causality_expectation: 'expectation code', }] }] ) #TODO source of information #TODO value sets allergy.criticality.should == 'fatal' allergy.sensitivity_type.should == 'allergy' allergy.recorded_date.should be_within(10.seconds).of(Time.now) allergy.status.should == 'status' allergy.substance.type.codings.first.system_name.should == 'RxNorm' end end
skoba/fhir-ruby
lib/fhir/selection.rb
<filename>lib/fhir/selection.rb module Fhir class Selection attr :graph def initialize(graph, selection) @graph = graph @selection = selection end def +(other) if other.graph != graph raise "Could not sum selections with different graphs" end if other.respond_to?(:to_a) selection(to_a + other.to_a) else raise 'Could not add selections' end end def flatten selection(@selection.to_a.flatten) end def map(&block) selection(@selection.map do |node| res = block.call(node) if res.is_a?(Fhir::Selection) res.to_a else res end end) end def method_missing(name, *args, &block) if mod.respond_to?(name) mod.send(name, self, *args, &block) elsif @selection.respond_to?(name) selection(@selection.send(name, *args, &block)) else super end end def to_a @selection.to_a end def respond_to_missing?(method, include_private = false) mod.respond_to?(method) || @selection.respond_to?(method) end def inspect "<Selection: #{@selection}>" end def selection(sel) Selection.new(@graph, sel) end private def mod @mod ||= Module.new.tap do |mod| mod.send(:extend, SelecionFunctions) mod.send(:extend, TemplateFunctions) @graph.modules.each {|m| mod.send(:extend, m) } end end end end
skoba/fhir-ruby
spec/path_spec.rb
require 'spec_helper' describe Fhir::Path do let(:p) { Fhir::Path } example do path = p.new(%w[a b c]) subpath = p.new(%w[a b c d e]) relative_path = p.new(%w[d e]) path.to_s.should == 'a.b.c' path.subpath?(subpath).should be_true path.include?(subpath).should be_true (subpath < path).should be_true (subpath > path).should be_false subpath.relative(path).should == relative_path -> { path.relative(subpath).should == relative_path }.should raise_error(/not subpath/) (subpath - path).should == relative_path path.concat(relative_path).should == subpath (path + relative_path).should == subpath new_path = path.dup new_path.to_a.should == path.to_a end it 'should initialize by both array and another path' do path1 = Fhir::Path.new([1, 2, 3]) path2 = Fhir::Path.new(path1) path1.should == path2 end end
skoba/fhir-ruby
spec/sources_spec.rb
require 'spec_helper' describe 'Graph sources' do let(:graph) { Fhir.graph } let(:selection) { Fhir.graph.selection } it 'should parse xml data' do node = selection.node(['Condition']) node.max.should == '1' node.min.should == '1' node.attributes[:comment].should_not be_empty node.children.to_a.length.should == 22 end it 'should expand datatypes' do node = selection.node(%w[Practitioner address]) node.children.to_a.should_not be_empty end it 'should expand datatypes' do selection.node(%w[MedicationStatement identifier]) end end
skoba/fhir-ruby
spec/selection_spec.rb
require 'spec_helper' describe 'Fhir::Selection' do module TestSelection def my_selection(selection) selection end end let(:graph) do Object.new.tap do |g| g.stub(:modules).and_return([TestSelection]) end end example do initial_selection = Object.new selection = Fhir::Selection.new(graph, initial_selection) selection.should respond_to(:my_selection) selection.my_selection.should == selection end it 'should add two selections' do sum = Fhir::Selection.new(graph, [42]) + Fhir::Selection.new(graph, [7]) sum.should be_a(Fhir::Selection) sum.to_a.should == [42, 7] end it 'should flatten' do Fhir::Selection.new(graph, [[42]]).flatten.to_a.should == [42] end end
skoba/fhir-ruby
lib/fhir/cli.rb
<gh_stars>1-10 require 'ostruct' module Fhir class Cli def initialize(file) raise "Could not find configuratin file - #{file}" unless File.exists?(file) self.instance_eval File.read(file), file end def configure(&block) Fhir.configure(&block) end def generate(&block) Fhir.generate(&block) end end end
skoba/fhir-ruby
spec/templates_spec.rb
require 'spec_helper' describe 'Fhir::TemplateFunctions' do let(:graph) do Fhir::Graph.new.tap do |g| g.add([1]) g.add([1, 2]) end end let(:selection) { graph.selection } it 'should render template' do selection .template { "item: <%= node.path -%>" } .render .should == "item: 1\nitem: 1.2" end it 'should render template from file' do selection .template(path: "#{File.dirname(__FILE__)}/template.erb") .render .should == "item: 1\nitem: 1.2" end it 'should render to file' do tmp_folder = File.join(File.dirname(__FILE__), 'tmp/models') FileUtils.rm_rf(tmp_folder) selection .template { "item: <%= node.path -%>" } .file(tmp_folder) do |node| "#{node.path}.txt" end File.exists?("#{tmp_folder}/1.txt").should be_true File.exists?("#{tmp_folder}/1.2.txt").should be_true File.open("#{tmp_folder}/1.txt").readlines.first.should == 'item: 1' File.open("#{tmp_folder}/1.2.txt").readlines.first.should == 'item: 1.2' end end
skoba/fhir-ruby
spec/graph_spec.rb
<reponame>skoba/fhir-ruby require 'spec_helper' describe Fhir::Graph do subject { Fhir::Graph.new(modules: Module.new, node_modules: Module.new) } it 'should add nodes' do subject.add(['one', 'two', 'three']) node = subject.nodes.first node.should be_a(Fhir::Node) node.path.should == ['one', 'two', 'three'] end it 'should apply rules' do subject.add([42], max: 7) subject.rule([42], max: -1) node = subject.nodes.first node.max.should == -1 end end
skoba/fhir-ruby
example_project/gen/selection_functions.rb
module SelectionFunctions def reject_idrefs(selection) selection.select do |n| n.type != 'xmlIdRef' end end def reject_contained(selection) selection.select do |n| n.name != 'contained' end end def simple_types(selection) selection.select do |n| n.type =~ /^[a-z].*/ end end def value_objects(selection) selection .by_attr('type', 'Resource') .map(&:embedded_descendants) .flatten end def sorted(selection) selection.sort_by(&:path) end def tables(selection) resources = selection.by_attr('type', 'Resource') resources + resources.map(&:associations).flatten end def models(selection) selection.tables end def resource_refs(selection) selection.select(&:resource_ref?) end end
shirasagi/opendata
lib/opendata/api.rb
<reponame>shirasagi/opendata<gh_stars>1-10 module Opendata::Api public def check_num(num, messages) if num if integer?(num) if num.to_i < 0 messages << "Must be a natural number" end else messages << "Invalid integer" end end end def integer?(s) i = Integer(s) check = true rescue check = false end def convert_packages(datasets) packages = [] if datasets datasets.each do |dataset| packages << convert_package(dataset) end end return packages end def convert_package(dataset) package = {} author, author_email = get_author(dataset) # special attributes conversion package[:author] = author package[:author_email] = author_email package[:type] = "dataset" package[:resources] = convert_resources(dataset[:resources]) + convert_url_resources(dataset[:url_resources]) package[:num_resources] = get_num_resources(dataset[:resources]) + get_num_url_resources(dataset[:url_resources]) package[:tags] = convert_tags(dataset) package[:groups] = convert_dataset_groups(dataset[:dataset_group_ids]) # map attributes [ [ :private, :state ], [ :revision_timestamp, :released ], [ :id, :_id ], [ :metadata_created, :created ], [ :metadata_modified, :updated ], [ :license_id, :license ], [ :name, :name ], [ :notes, :text ], [ :title, :name ] ].each do |to, from| package[to] = dataset[from] end # simply copy attributes [ :permission_level, :member_id, :user_id, :site_id, :filename, :route, :depth, :order, :category_ids, :area_ids, :related_page_ids, :related_url, :point, :downloaded ].each do |k| package[k] = dataset[k] end return package end def get_num_resources(dataset_resources) return dataset_resources ? dataset_resources.size : 0 end def convert_resources(dataset_resources) package_resources = [] resources = dataset_resources || [] resources.each do |resource| package_resources << convert_resource(resource) end return package_resources end def convert_resource(resource) package_resource = {} package_resource[:id] = resource[:file_id] package_resource[:last_modified] = resource[:updated] package_resource[:description] = resource[:text] package_resource[:format] = resource[:format] package_resource[:name] = resource[:name] package_resource[:created] = resource[:created] package_resource[:filename] = resource[:filename] package_resource[:license_id] = resource[:license_id] package_resource[:rdf_iri] = resource[:rdf_iri] package_resource[:rdf_error] = resource[:rdf_error] return package_resource end def get_num_url_resources(dataset_url_resources) return dataset_url_resources ? dataset_url_resources.size : 0 end def convert_url_resources(dataset_url_resources) package_url_resources = [] url_resources = dataset_url_resources || [] url_resources.each do |url_resource| package_url_resources << convert_url_resource(url_resource) end return package_url_resources end def convert_url_resource(url_resource) package_url_resource = {} package_url_resource[:id] = url_resource[:file_id] package_url_resource[:last_modified] = url_resource[:updated] package_url_resource[:description] = url_resource[:text] package_url_resource[:format] = url_resource[:format] package_url_resource[:name] = url_resource[:name] package_url_resource[:created] = url_resource[:created] package_url_resource[:filename] = url_resource[:filename] package_url_resource[:license_id] = url_resource[:license_id] package_url_resource[:rdf_iri] = url_resource[:rdf_iri] package_url_resource[:rdf_error] = url_resource[:rdf_error] package_url_resource[:originai_url] = url_resource[:original_url] package_url_resource[:original_updated] = url_resource[:original_updated] package_url_resource[:crawl_state] = url_resource[:crawl_state] package_url_resource[:crawl_update] = url_resource[:crawl_update] return package_url_resource end def convert_tags(dataset) package_tags = [] tags = dataset[:tags] || [] tags.each do |tag| package_tag = {} package_tag[:display_name] = tag package_tag[:name] = tag package_tag[:revision_timestamp] = dataset[:released] package_tag[:state] = dataset[:state] package_tags << package_tag end return package_tags end def convert_dataset_groups(dataset_group_ids) package_groups = [] group_ids = dataset_group_ids || [] group_ids.each do |group_id| package_groups << convert_dataset_group(group_id) end return package_groups end def convert_dataset_group(group_id) package_group = {} dataset_group = Opendata::DatasetGroup.site(@cur_site).public.where(id: group_id).first if dataset_group package_group[:display_name] = dataset_group[:name] package_group[:title] = dataset_group[:name] package_group[:id] = dataset_group[:_id] package_group[:name] = dataset_group[:name] end return package_group end def get_member(member_id) package_member = {} member = Opendata::Member.site(@cur_site).where(id: member_id).first if member package_member[:author] = member[:name] package_member[:author_email] = member[:email] end return package_member end def get_user(user_id) package_user = {} user = Cms::User.site(@cur_site).where(id: user_id).first if user package_user[:author] = user[:name] package_user[:author_email] = user[:email] end return package_user end def get_author(dataset) if member_id = dataset[:member_id] member = get_member(member_id) return [ member[:author], member[:author_email] ] elsif user_id = dataset[:user_id] user = get_user(user_id) return [ user[:author], user[:author_email] ] end nil end end
shirasagi/opendata
spec/models/chorg/test_runner_spec.rb
<reponame>shirasagi/opendata require 'spec_helper' describe Chorg::TestRunner, dbscope: :example do let(:root_group) { create(:revision_root_group) } let(:site) { create(:cms_site, group_ids: [root_group.id]) } context "with add" do let(:revision) { create(:revision, site_id: site.id) } let(:changeset) { create(:add_changeset, revision_id: revision.id) } subject { described_class.new } it do expect(revision).not_to be_nil expect(changeset).not_to be_nil expect { subject.call(site.host, nil, revision.name, 1) }.not_to raise_error expect(Cms::Group.where(name: changeset.destinations.first["name"]).first).to be_nil end end context "with move" do let(:group) { create(:revision_new_group) } let(:revision) { create(:revision, site_id: site.id) } let(:changeset) { create(:move_changeset, revision_id: revision.id, source: group) } context "with Article::Page" do let(:page) { create(:revisoin_page, site: site, group: group) } subject { described_class.new } it do # ensure create models expect(changeset).not_to be_nil expect(page).not_to be_nil # check for not changed expect { subject.call(site.host, nil, revision.name, 1) }.not_to raise_error expect(Cms::Group.where(id: group.id).first).not_to be_nil expect(Cms::Group.where(id: group.id).first.name).to eq changeset.sources.first["name"] page.reload expect(page.group_ids).to eq [ group.id ] expect(page.contact_group_id).to eq group.id expect(page.contact_email).to eq group.contact_email expect(page.contact_tel).to eq group.contact_tel expect(page.contact_fax).to eq group.contact_fax end end end context "with unify" do let(:group1) { create(:revision_new_group) } let(:group2) { create(:revision_new_group) } let(:user1) { create(:cms_user, name: "#{unique_id}", email: <EMAIL>", group_ids: [group1.id]) } let(:user2) { create(:cms_user, name: "#{unique_id}", email: <EMAIL>", group_ids: [group2.id]) } let(:revision) { create(:revision, site_id: site.id) } let(:changeset) { create(:unify_changeset, revision_id: revision.id, sources: [group1, group2]) } context "with Article::Page" do let(:page) { create(:revisoin_page, site: site, group: group1) } subject { described_class.new } it do # ensure create models expect(user1).not_to be_nil expect(user2).not_to be_nil expect(revision).not_to be_nil expect(changeset).not_to be_nil expect(page).not_to be_nil # check for not changed expect { subject.call(site.host, user1.id, revision.name, 1) }.not_to raise_error expect(Cms::Group.where(id: group1.id).first).not_to be_nil expect(Cms::Group.where(id: group1.id).first.name).to eq group1.name expect(Cms::Group.where(id: group2.id).first).not_to be_nil expect(Cms::Group.where(id: group2.id).first.name).to eq group2.name page.reload expect(page.group_ids).to eq [ group1.id ] expect(page.contact_group_id).to eq group1.id expect(page.contact_email).to eq group1.contact_email expect(page.contact_tel).to eq group1.contact_tel expect(page.contact_fax).to eq group1.contact_fax user1.reload expect(user1.group_ids).to eq [group1.id] user2.reload expect(user2.group_ids).to eq [group2.id] end end end context "with delete" do let(:group) { create(:revision_new_group) } let(:revision) { create(:revision, site_id: site.id) } let(:changeset) { create(:delete_changeset, revision_id: revision.id, source: group) } subject { described_class.new } it do # ensure create models expect(changeset).not_to be_nil # change group. expect { subject.call(site.host, nil, revision.name, 1) }.not_to raise_error # check for not changed expect(Cms::Group.where(id: group.id).first).not_to be_nil end end end
shirasagi/opendata
app/models/concerns/ss/user_permission.rb
module SS::UserPermission extend ActiveSupport::Concern public def allowed?(action, user, opts = {}) return true if new_record? user_id == user.id end module ClassMethods public def allowed?(action, user, opts = {}) self.new.allowed?(action, user, opts) end def allow(action, user, opts = {}) where(user_id: user.id) end end end
shirasagi/opendata
app/models/ezine/sent_log.rb
class Ezine::SentLog include SS::Document field :email, type: String, metadata: { from: :email } belongs_to :page, class_name: "Ezine::Page" belongs_to :node, class_name: "Cms::Node" end
shirasagi/opendata
app/models/voice/synthesis_job.rb
<gh_stars>1-10 require 'bson' require 'open-uri' class Voice::SynthesisJob include Job::Worker self.job_options = { 'pool' => 'voice_synthesis' } public def call(id_or_url, force = false) voice_file = Voice::File.find(id_or_url) rescue nil voice_file ||= Voice::File.find_or_create_by_url(id_or_url) return unless voice_file begin Rails.logger.info("synthesize: #{voice_file.url}") voice_file.synthesize force rescue OpenURI::HTTPError, TimeoutError # do not record http errors like 404, 500. voice_file.destroy raise end end def self.purge_pending_tasks criteria = Job::Task.where(pool: 'voice_synthesis') return if criteria.count < 20 count = criteria.where(started: nil).lt(created: 5.minutes.ago).destroy Rails.logger.info("purged #{count} voice task(s)") count end end
shirasagi/opendata
app/controllers/cms/node/import_controller.rb
<reponame>shirasagi/opendata class Cms::Node::ImportController < ApplicationController include Cms::BaseFilter include Cms::CrudFilter model Cms::Node::ImportNode navi_view "cms/node/import_pages/navi" menu_view nil before_action :set_item public def import @item.attributes = get_params @item.cur_site = @cur_site result = @item.import flash.now[:notice] = t("views.notice.saved") if !result && @item.imported > 0 render_create result, location: redirect_url, render: { file: :index } end private def set_item @item = @cur_node.becomes_with_route("cms/import_node") end def redirect_url node_import_pages_path(cid: @cur_node) end end
shirasagi/opendata
spec/features/cms/groups_spec.rb
require 'spec_helper' describe "cms_groups" do subject(:site) { cms_site } subject(:item) { Cms::Group.last } subject(:index_path) { cms_groups_path site.host } subject(:new_path) { new_cms_group_path site.host } subject(:show_path) { cms_group_path site.host, item } subject(:edit_path) { edit_cms_group_path site.host, item } subject(:delete_path) { delete_cms_group_path site.host, item } subject(:import_path) { import_cms_groups_path site.host } it "without login" do visit index_path expect(current_path).to eq sns_login_path end it "without auth" do login_ss_user visit index_path expect(status_code).to eq 403 end context "with auth" do before { login_cms_user } it "#index" do visit index_path expect(current_path).not_to eq sns_login_path end it "#new" do visit new_path within "form#item-form" do fill_in "item[name]", with: "cms_group/sample" click_button "保存" end expect(status_code).to eq 200 expect(current_path).not_to eq new_path expect(page).not_to have_css("form#item-form") end it "#show" do visit show_path expect(status_code).to eq 200 expect(current_path).not_to eq sns_login_path end it "#edit" do visit edit_path within "form#item-form" do fill_in "item[name]", with: "cms_group/modify" click_button "保存" end expect(current_path).not_to eq sns_login_path expect(page).not_to have_css("form#item-form") end it "#delete" do visit delete_path within "form" do click_button "削除" end expect(current_path).to eq index_path end end context "import from csv" do before(:each) do tel = "000-000-0000" email = "<EMAIL>" g1 = create(:cms_group, name: "A", order: 10, contact_tel: tel, contact_fax: tel, contact_email: email) cms_site.add_to_set(group_ids: [g1.id]) end it "#import" do login_cms_user visit import_path within "form" do attach_file "item[in_file]", "#{Rails.root}/spec/fixtures/cms/group/cms_groups_1.csv" click_button "インポート" end expect(status_code).to eq 200 expect(current_path).to eq index_path groups = Cms::Group.site(cms_site).ne(id: cms_group.id) expected_names = %w(A A/B A/B/C A/B/C/D A/E A/E/F A/E/G) expected_orders = %w(10 20 30 40 50 60 70).map(&:to_i) expected_contact_tels = %w(1 2 3 4 5 6 7).fill("000-000-0000") expected_contact_faxs = %w(1 2 3 4 5 6 7).fill("000-000-0000") expected_contact_emails = %w(1 2 3 4 5 6 7).fill("<EMAIL>") expect(groups.map(&:name)).to eq expected_names expect(groups.map(&:order)).to eq expected_orders expect(groups.map(&:contact_tel)).to eq expected_contact_tels expect(groups.map(&:contact_fax)).to eq expected_contact_faxs expect(groups.map(&:contact_email)).to eq expected_contact_emails end end end
shirasagi/opendata
spec/models/opendata/dataset_spec.rb
<reponame>shirasagi/opendata<gh_stars>1-10 require 'spec_helper' describe Opendata::Dataset, dbscope: :example do let!(:node_category) { create(:opendata_node_category) } let!(:node_search_dataset) { create(:opendata_node_search_dataset) } let(:node) { create(:opendata_node_dataset) } context "check attributes with typical url resource" do subject { create(:opendata_dataset, node: node) } its(:becomes_with_route) { is_expected.not_to be_nil } its(:dirname) { is_expected.to eq node.filename } its(:basename) { is_expected.to eq subject.filename.split('/').last } its(:path) { is_expected.to end_with "/#{subject.dirname}/#{subject.basename}" } its(:url) { is_expected.to eq "/#{subject.dirname}/#{subject.basename}" } its(:full_url) { is_expected.to eq "http://#{cms_site.domain}/#{subject.dirname}/#{subject.basename}" } its(:parent) { expect(subject.parent.id).to eq node.id } its(:point_url) { is_expected.to eq "#{subject.url.sub(/\.html$/, "")}/point.html" } its(:point_members_url) { is_expected.to eq "#{subject.url.sub(/\.html$/, "")}/point/members.html" } its(:dataset_apps_url) { is_expected.to eq "#{subject.url.sub(/\.html$/, "")}/apps/show.html" } its(:dataset_ideas_url) { is_expected.to eq "#{subject.url.sub(/\.html$/, "")}/ideas/show.html" } its(:contact_present?) { is_expected.to be_falsey } end describe ".sort_options" do it { expect(described_class.sort_options).to include %w(新着順 released) } end describe ".sort_hash" do it { expect(described_class.sort_hash("released")).to include(released: -1).and include(_id: -1) } it { expect(described_class.sort_hash("popular")).to include(point: -1).and include(_id: -1) } it { expect(described_class.sort_hash("attention")).to include(downloaded: -1).and include(_id: -1) } it { expect(described_class.sort_hash("")).to include(released: -1) } it { expect(described_class.sort_hash("foobar")).to include("foobar" => 1) } end describe ".aggregate_field" do it { expect(described_class.aggregate_field(:license, limit: 10)).to be_empty } end describe ".aggregate_array" do it { expect(described_class.aggregate_array(:tags, limit: 10)).to be_empty } end describe ".aggregate_resources" do it { expect(described_class.aggregate_resources(:format, limit: 10)).to be_empty } end describe ".get_tag_list" do it { expect(described_class.get_tag_list(nil)).to be_empty } end describe ".get_tag" do it { expect(described_class.get_tag("タグ")).to be_empty } end describe ".search" do context 'with no option' do let(:category_id_params) do { site: node_category.site, category_id: node_category.id.to_s } end let(:ids_matcher) do include("_id" => include("$in" => include(11).and(include(31)))) end let(:normal_keyword_matcher) do include("$and" => include("$or" => include("name" => /キーワード/i).and(include("text" => /キーワード/i)))) end let(:normal_name_keyword_matcher) do include("$and" => include("$or" => include("name" => /キーワード/i).and(include("text" => /キーワード/i)))) end let(:normal_name_modal_matcher) do include("name" => include("$all" => include(/名前/i))) end let(:meta_name_keyword_matcher) do include("$and" => include("$or" => include("name" => /\(\)\[\]\{\}\.\?\+\*\|\\/i). and(include("text" => /\(\)\[\]\{\}\.\?\+\*\|\\/i)))) end let(:meta_name_modal_matcher) do include("name" => include("$all" => include(/\(\)\[\]\{\}\.\?\+\*\|\\/i))) end let(:category_id_matcher) do include("$and" => include("category_ids" => include("$in" => include(node_category.id)))) end let(:dataset_group_matcher) do include("$and" => include("dataset_group_ids" => include("$in" => include(-1)))) end let(:format_matcher) do include("$and" => include("$or" => include("resources.format" => "CSV").and(include("url_resources.format" => "CSV")))) end let(:license_id_matcher) do include("$and" => include("$or" => include("resources.license_id" => 28).and(include("url_resources.license_id" => 28)))) end it { expect(described_class.search({}).selector.to_h).to include("route" => "opendata/dataset") } it { expect(described_class.search(keyword: "キーワード").selector.to_h).to normal_keyword_matcher } it { expect(described_class.search(ids: "11,31").selector.to_h).to ids_matcher } it { expect(described_class.search(name: "名前", keyword: "キーワード").selector.to_h).to normal_name_keyword_matcher } it { expect(described_class.search(name: "名前", modal: true).selector.to_h).to normal_name_modal_matcher } it { expect(described_class.search(name: "名前", keyword: "()[]{}.?+*|\\").selector.to_h).to meta_name_keyword_matcher } it { expect(described_class.search(name: "()[]{}.?+*|\\", modal: true).selector.to_h).to meta_name_modal_matcher } it { expect(described_class.search(tag: "タグ").selector.to_h).to include("$and" => include("tags" => "タグ")) } it { expect(described_class.search(area_id: "43").selector.to_h).to include("$and" => include("area_ids" => 43)) } it { expect(described_class.search(category_id_params).selector.to_h).to category_id_matcher } it { expect(described_class.search(dataset_group: "データセット", site: cms_site).selector.to_h).to dataset_group_matcher } it { expect(described_class.search(format: "csv").selector.to_h).to format_matcher } it { expect(described_class.search(license_id: "28").selector.to_h).to license_id_matcher } end context 'with all_keywords option' do let(:category_id_params) do { site: node_category.site, category_id: node_category.id.to_s, option: 'all_keywords' } end let(:ids_matcher) do include("_id" => include("$in" => include(11).and(include(31)))) end let(:normal_keyword_matcher) do include("$and" => include("$or" => include("name" => /キーワード/i).and(include("text" => /キーワード/i)))) end # let(:normal_name_keyword_matcher) do # include("$and" => include("$or" => include("name" => /キーワード/i).and(include("text" => /キーワード/i)))) # end # let(:normal_name_modal_matcher) do # include("name" => include("$all" => include(/名前/i))) # end # let(:meta_name_keyword_matcher) do # include("$and" => include("$or" => include("name" => /\(\)\[\]\{\}\.\?\+\*\|\\/i). # and(include("text" => /\(\)\[\]\{\}\.\?\+\*\|\\/i)))) # end # let(:meta_name_modal_matcher) do # include("name" => include("$all" => include(/\(\)\[\]\{\}\.\?\+\*\|\\/i))) # end let(:category_id_matcher) do include("$and" => include("category_ids" => include("$in" => include(node_category.id)))) end let(:tag_params) { { tag: "タグ", option: 'all_keywords' } } let(:tag_matcher) { include("$and" => include("tags" => "タグ")) } let(:area_id_params) { { area_id: "43", option: 'all_keywords' } } let(:area_id_matcher) { include("$and" => include("area_ids" => 43)) } let(:dataset_group_params) { { dataset_group: "データセット", site: cms_site, option: 'all_keywords' } } let(:dataset_group_matcher) do include("$and" => include("dataset_group_ids" => include("$in" => include(-1)))) end let(:format_matcher) do include("$and" => include("$or" => include("resources.format" => "CSV").and(include("url_resources.format" => "CSV")))) end let(:license_id_matcher) do include("$and" => include("$or" => include("resources.license_id" => 28).and(include("url_resources.license_id" => 28)))) end it { expect(described_class.search({}).selector.to_h).to include("route" => "opendata/dataset") } it { expect(described_class.search(keyword: "キーワード", option: 'all_keywords').selector.to_h).to normal_keyword_matcher } it { expect(described_class.search(ids: "11,31", option: 'all_keywords').selector.to_h).to ids_matcher } # it { expect(described_class.search(name: "名前", keyword: "キーワード").selector.to_h).to normal_name_keyword_matcher } # it { expect(described_class.search(name: "名前", modal: true).selector.to_h).to normal_name_modal_matcher } # it { expect(described_class.search(name: "名前", keyword: "()[]{}.?+*|\\").selector.to_h).to meta_name_keyword_matcher } # it { expect(described_class.search(name: "()[]{}.?+*|\\", modal: true).selector.to_h).to meta_name_modal_matcher } it { expect(described_class.search(tag_params).selector.to_h).to tag_matcher } it { expect(described_class.search(area_id_params).selector.to_h).to area_id_matcher } it { expect(described_class.search(category_id_params).selector.to_h).to category_id_matcher } it { expect(described_class.search(dataset_group_params).selector.to_h).to dataset_group_matcher } it { expect(described_class.search(format: "csv", option: 'all_keywords').selector.to_h).to format_matcher } it { expect(described_class.search(license_id: "28", option: 'all_keywords').selector.to_h).to license_id_matcher } end context 'with any_keywords option' do let(:category_id_params) do { site: node_category.site, category_id: node_category.id.to_s, option: 'any_keywords' } end let(:ids_matcher) do include("_id" => include("$in" => include(11).and(include(31)))) end let(:normal_keyword_matcher) do include("$or" => include("$or" => include("name" => /キーワード/i).and(include("text" => /キーワード/i)))) end # let(:normal_name_keyword_matcher) do # include("$and" => include("$or" => include("name" => /キーワード/i).and(include("text" => /キーワード/i)))) # end # let(:normal_name_modal_matcher) do # include("name" => include("$all" => include(/名前/i))) # end # let(:meta_name_keyword_matcher) do # include("$and" => include("$or" => include("name" => /\(\)\[\]\{\}\.\?\+\*\|\\/i). # and(include("text" => /\(\)\[\]\{\}\.\?\+\*\|\\/i)))) # end # let(:meta_name_modal_matcher) do # include("name" => include("$all" => include(/\(\)\[\]\{\}\.\?\+\*\|\\/i))) # end let(:category_id_matcher) do include("$and" => include("category_ids" => include("$in" => include(node_category.id)))) end let(:tag_params) { { tag: "タグ", option: 'any_keywords' } } let(:tag_matcher) { include("$and" => include("tags" => "タグ")) } let(:area_id_params) { { area_id: "43", option: 'any_keywords' } } let(:area_id_matcher) { include("$and" => include("area_ids" => 43)) } let(:dataset_group_params) { { dataset_group: "データセット", site: cms_site, option: 'any_keywords' } } let(:dataset_group_matcher) do include("$and" => include("dataset_group_ids" => include("$in" => include(-1)))) end let(:format_matcher) do include("$and" => include("$or" => include("resources.format" => "CSV").and(include("url_resources.format" => "CSV")))) end let(:license_id_matcher) do include("$and" => include("$or" => include("resources.license_id" => 28).and(include("url_resources.license_id" => 28)))) end it { expect(described_class.search({}).selector.to_h).to include("route" => "opendata/dataset") } it { expect(described_class.search(keyword: "キーワード", option: 'any_keywords').selector.to_h).to normal_keyword_matcher } it { expect(described_class.search(ids: "11,31", option: 'any_keywords').selector.to_h).to ids_matcher } # it { expect(described_class.search(name: "名前", keyword: "キーワード").selector.to_h).to normal_name_keyword_matcher } # it { expect(described_class.search(name: "名前", modal: true).selector.to_h).to normal_name_modal_matcher } # it { expect(described_class.search(name: "名前", keyword: "()[]{}.?+*|\\").selector.to_h).to meta_name_keyword_matcher } # it { expect(described_class.search(name: "()[]{}.?+*|\\", modal: true).selector.to_h).to meta_name_modal_matcher } it { expect(described_class.search(tag_params).selector.to_h).to tag_matcher } it { expect(described_class.search(area_id_params).selector.to_h).to area_id_matcher } it { expect(described_class.search(category_id_params).selector.to_h).to category_id_matcher } it { expect(described_class.search(dataset_group_params).selector.to_h).to dataset_group_matcher } it { expect(described_class.search(format: "csv", option: 'any_keywords').selector.to_h).to format_matcher } it { expect(described_class.search(license_id: "28", option: 'any_keywords').selector.to_h).to license_id_matcher } end context 'with any_conditions option' do let(:category_id_params) do { site: node_category.site, category_id: node_category.id.to_s, option: 'any_conditions' } end let(:ids_matcher) do include("_id" => include("$in" => include(11).and(include(31)))) end let(:normal_keyword_matcher) do include("$or" => include("$or" => include("name" => /キーワード/i).and(include("text" => /キーワード/i)))) end # let(:normal_name_keyword_matcher) do # include("$and" => include("$or" => include("name" => /キーワード/i).and(include("text" => /キーワード/i)))) # end # let(:normal_name_modal_matcher) do # include("name" => include("$all" => include(/名前/i))) # end # let(:meta_name_keyword_matcher) do # include("$and" => include("$or" => include("name" => /\(\)\[\]\{\}\.\?\+\*\|\\/i). # and(include("text" => /\(\)\[\]\{\}\.\?\+\*\|\\/i)))) # end # let(:meta_name_modal_matcher) do # include("name" => include("$all" => include(/\(\)\[\]\{\}\.\?\+\*\|\\/i))) # end let(:category_id_matcher) do include("$or" => include("category_ids" => include("$in" => include(node_category.id)))) end let(:tag_params) { { tag: "タグ", option: 'any_conditions' } } let(:tag_matcher) { include("$or" => include("tags" => "タグ")) } let(:area_id_params) { { area_id: "43", option: 'any_conditions' } } let(:area_id_matcher) { include("$or" => include("area_ids" => 43)) } let(:dataset_group_params) { { dataset_group: "データセット", site: cms_site, option: 'any_conditions' } } let(:dataset_group_matcher) do include("$or" => include("dataset_group_ids" => include("$in" => include(-1)))) end let(:format_matcher) do include("$or" => include("$or" => include("resources.format" => "CSV").and(include("url_resources.format" => "CSV")))) end let(:license_id_matcher) do include("$or" => include("$or" => include("resources.license_id" => 28).and(include("url_resources.license_id" => 28)))) end it { expect(described_class.search({}).selector.to_h).to include("route" => "opendata/dataset") } it { expect(described_class.search(keyword: "キーワード", option: 'any_conditions').selector.to_h).to normal_keyword_matcher } it { expect(described_class.search(ids: "11,31", option: 'any_conditions').selector.to_h).to ids_matcher } # it { expect(described_class.search(name: "名前", keyword: "キーワード").selector.to_h).to normal_name_keyword_matcher } # it { expect(described_class.search(name: "名前", modal: true).selector.to_h).to normal_name_modal_matcher } # it { expect(described_class.search(name: "名前", keyword: "()[]{}.?+*|\\").selector.to_h).to meta_name_keyword_matcher } # it { expect(described_class.search(name: "()[]{}.?+*|\\", modal: true).selector.to_h).to meta_name_modal_matcher } it { expect(described_class.search(tag_params).selector.to_h).to tag_matcher } it { expect(described_class.search(area_id_params).selector.to_h).to area_id_matcher } it { expect(described_class.search(category_id_params).selector.to_h).to category_id_matcher } it { expect(described_class.search(dataset_group_params).selector.to_h).to dataset_group_matcher } it { expect(described_class.search(format: "csv", option: 'any_conditions').selector.to_h).to format_matcher } it { expect(described_class.search(license_id: "28", option: 'any_conditions').selector.to_h).to license_id_matcher } end end describe ".format_options" do context "empty dataset" do it { expect(described_class.format_options).to eq [] } end context "CSV Resource" do let(:file) { Rails.root.join("spec", "fixtures", "opendata", "shift_jis.csv") } let(:content_type) { "application/vnd.ms-excel" } let(:license_logo_file) { Rails.root.join("spec", "fixtures", "ss", "logo.png") } before do license = Fs::UploadedFile.create_from_file(license_logo_file, basename: "spec") do |uploaded_file| create(:opendata_license, site: node.site, file: uploaded_file) end dataset = create(:opendata_dataset, node: node) resource = dataset.resources.new(attributes_for(:opendata_resource)) Fs::UploadedFile.create_from_file(file, basename: "spec", content_type: content_type) do |uploaded_file| resource.in_file = uploaded_file resource.license_id = license.id resource.save! end end it { expect(described_class.format_options).to include(%w(CSV CSV)) } end end end
shirasagi/opendata
app/helpers/cms/node_helper.rb
<reponame>shirasagi/opendata module Cms::NodeHelper def contents_path(node) route = node.view_route.present? ? node.view_route : node.route "/.#{node.site.host}/" + route.pluralize.sub("/", "#{node.id}/") rescue StandardError => e raise(e) unless Rails.env.production? node_nodes_path(cid: node) end def node_navi(opts = {}, &block) h = [] if block_given? h << capture(&block) end h << render(partial: "cms/node/main/node_navi") h << render(partial: "cms/node/main/modules") #h << render(partial: "cms/main/navi") h.join.html_safe end end
shirasagi/opendata
app/models/ezine/member.rb
class Ezine::Member include SS::Document include SS::Reference::User include SS::Reference::Site include Cms::SitePermission include Ezine::MemberSearchable include Ezine::Addon::Data field :email, type: String, metadata: { from: :email } field :email_type, type: String field :state, type: String, default: 'enabled' permit_params :email, :email_type, :state belongs_to :node, class_name: "Cms::Node" validates :email, uniqueness: { scope: :node_id }, presence: true, email: true validates :email_type, inclusion: { in: %w(text html) } validates :state, inclusion: { in: %w(enabled disabled) } scope :enabled, ->{ where(state: 'enabled') } public def email_type_options [ [I18n.t('ezine.options.email_type.text'), 'text'], [I18n.t('ezine.options.email_type.html'), 'html'], ] end def state_options [ [I18n.t('ezine.options.delivery_state.enabled'), 'enabled'], [I18n.t('ezine.options.delivery_state.disabled'), 'disabled'], ] end def test_member? false end end
shirasagi/opendata
spec/features/cms/files_spec.rb
<filename>spec/features/cms/files_spec.rb<gh_stars>1-10 require 'spec_helper' describe "cms_files" do let(:site) { cms_site } let(:item) { Cms::File.last } let(:index_path) { cms_files_path site.host } let(:new_path) { new_cms_file_path site.host } let(:show_path) { cms_file_path site.host, item } let(:edit_path) { edit_cms_file_path site.host, item } let(:delete_path) { delete_cms_file_path site.host, item } it "without login" do visit index_path expect(current_path).to eq sns_login_path end it "without auth" do login_ss_user visit index_path expect(status_code).to eq 403 end context "with auth" do before { login_cms_user } it "#index" do visit index_path expect(status_code).to eq 200 expect(current_path).not_to eq sns_login_path end it "#new" do visit new_path within "form#item-form" do attach_file "item[in_files][]", "#{Rails.root}/spec/fixtures/ss/logo.png" click_button "保存" end expect(status_code).to eq 200 expect(current_path).not_to eq new_path expect(page).not_to have_css("form#item-form") end it "#show" do visit show_path expect(status_code).to eq 200 expect(current_path).not_to eq sns_login_path end it "#edit" do visit edit_path within "form#item-form" do fill_in "item[filename]", with: "modify" click_button "保存" end expect(current_path).not_to eq sns_login_path expect(page).not_to have_css("form#item-form") end it "#delete" do visit delete_path within "form" do click_button "削除" end expect(current_path).to eq index_path end end end
shirasagi/opendata
config/routes/facility/routes.rb
<filename>config/routes/facility/routes.rb SS::Application.routes.draw do Facility::Initializer concern :deletion do get :delete, on: :member end concern :download do get :download, :on => :collection end concern :import do get :import, :on => :collection post :import, :on => :collection end content "facility" do get "/" => redirect { |p, req| "#{req.path}/searches" }, as: :main resources :pages, concerns: [:deletion, :download, :import] resources :nodes, concerns: :deletion resources :searches, concerns: :deletion resources :services, concerns: :deletion resources :locations, concerns: :deletion resources :categories, concerns: :deletion resources :images, concerns: :deletion resources :maps, concerns: :deletion end node "facility" do get "page/(index.:format)" => "public#index", cell: "nodes/page" get "node/(index.:format)" => "public#index", cell: "nodes/node" get "category/(index.:format)" => "public#index", cell: "nodes/category" get "service/(index.:format)" => "public#index", cell: "nodes/service" get "location/(index.:format)" => "public#index", cell: "nodes/location" get "search/(index.:format)" => "public#index", cell: "nodes/search" get "search/(map.:format)" => "public#map", cell: "nodes/search" get "search/(map-all.:format)" => "public#map_all", cell: "nodes/search" get "search/(result.:format)" => "public#result", cell: "nodes/search" end page "facility" do get "image/:filename.:format" => "public#index", cell: "pages/image" get "map/:filename.:format" => "public#index", cell: "pages/map" end namespace "facility", path: ".:site/facility" do namespace "apis" do get "categories" => "categories#index" get "locations" => "locations#index" get "services" => "services#index" end end namespace "facility", path: ".u:user/facility", module: "facility", servicer: /\d+/ do namespace "apis" do resources :temp_files, concerns: :deletion do get :select, on: :member get :view, on: :member get :thumb, on: :member get :download, on: :member end end end end
shirasagi/opendata
app/controllers/concerns/cms/base_filter.rb
module Cms::BaseFilter extend ActiveSupport::Concern include SS::BaseFilter included do cattr_accessor(:user_class) { Cms::User } helper Cms::NodeHelper helper Cms::FormHelper helper Cms::PathHelper before_action :set_site before_action :set_node before_action :set_group before_action :set_crumbs end private def set_site @cur_site = Cms::Site.find_by host: params[:site] @crumbs << [@cur_site.name, cms_contents_path] end def set_node return unless params[:cid] @cur_node = Cms::Node.site(@cur_site).find params[:cid] @cur_node.parents.each {|node| @crumbs << [node.name, view_context.contents_path(node)] } @crumbs << [@cur_node.name, view_context.contents_path(@cur_node)] end def set_group cur_groups = @cur_user.groups.in(name: @cur_site.groups.pluck(:name).map{ |name| /^#{Regexp.escape(name)}(\/|$)/ }) @cur_group = cur_groups.first # select one group raise "403" unless @cur_group end def set_crumbs # end public #def url_options # {}.merge(super) #end end
shirasagi/opendata
app/controllers/facility/agents/nodes/page_controller.rb
class Facility::Agents::Nodes::PageController < ApplicationController include Cms::NodeFilter::View public def map_pages Facility::Map.site(@cur_site).public. where(filename: /^#{@cur_node.filename}\//, depth: @cur_node.depth + 1).order_by(order: 1) end def image_pages Facility::Image.site(@cur_site).public. where(filename: /^#{@cur_node.filename}\//, depth: @cur_node.depth + 1).order_by(order: 1) end def index map_pages.each do |map| points = [] map.map_points.each_with_index do |point, i| points.push point image_ids = @cur_node.categories.pluck(:image_id) points[i][:image] = SS::File.in(id: image_ids).first.try(:url) end map.map_points = points if @merged_map @merged_map.map_points += map.map_points else @merged_map = map end end @summary_image = nil @images = [] image_pages.each do |page| next if page.image.blank? if @summary_image @images.push page else @summary_image = page end end end end
shirasagi/opendata
app/controllers/workflow/wizard_controller.rb
class Workflow::WizardController < ApplicationController include Cms::ApiFilter before_action :set_route, only: [:approver_setting] before_action :set_item, only: [:approver_setting] private def set_model @model = Cms::Page end def fix_params { cur_user: @cur_user, cur_site: @cur_site, cur_node: false } end def set_route route_id = params[:route_id] if "my_group" == route_id @route = nil else @route = Workflow::Route.find(params[:route_id]) end end def set_item @item = @model.find(params[:id]).becomes_with_route @item.attributes = fix_params end public def index render layout: false end def approver_setting if @route.present? if @item.apply_workflow?(@route) render file: "approver_setting_multi", layout: false else render json: @item.errors.full_messages, status: :bad_request end else render layout: false end end end
shirasagi/opendata
spec/features/opendata/dataset/csv2rdf_settings_spec.rb
<gh_stars>1-10 require 'spec_helper' describe "opendata_csv2rdf_settings", type: :feature, dbscope: :example do let(:site) { cms_site } let!(:node_search_dataset) { create(:opendata_node_search_dataset) } let(:node) { create(:opendata_node_dataset) } let(:dataset) { create(:opendata_dataset, node: node) } let(:license_logo_path) { Rails.root.join("spec", "fixtures", "ss", "logo.png") } let(:license_logo_file) { Fs::UploadedFile.create_from_file(license_logo_path, basename: "spec") } let(:license) { create(:opendata_license, site: site, file: license_logo_file) } let(:ipa_core_sample_file) { Rails.root.join("spec", "fixtures", "rdf", "ipa-core-sample.ttl") } before do # To stabilize spec, csv2tdf convert job is executed in-place process . allow(SS::RakeRunner).to receive(:run_async).and_wrap_original do |_, *args| config = { name: "default", model: "job:service", num_workers: 0, poll: %w(default voice_synthesis) } config.stringify_keys! Job::Service.run config end end before do # overwrite config to disable fuseki @save_fuseki = SS.config.opendata.fuseki SS::Config.replace_value_at(:opendata, :fuseki, "disable" => true) end after do SS::Config.replace_value_at(:opendata, :fuseki, @save_fuseki) end before do Rdf::VocabImportJob.new.call(site.host, "ic", ipa_core_sample_file, Rdf::Vocab::OWNER_SYSTEM, 1000) end before { login_cms_user } describe "convert csv to rdf" do let(:csv_file) { Rails.root.join("spec", "fixtures", "opendata", "shift_jis.csv") } let(:resource) { dataset.resources.new(attributes_for(:opendata_resource, license_id: license.id)) } before do Fs::UploadedFile.create_from_file(csv_file, basename: "spec") do |f| resource.in_file = f resource.save! end resource.reload end let(:header_size_path) { opendata_dataset_resource_header_size_path site.host, node.id, dataset.id, resource.id } let(:rdf_class_path) { opendata_dataset_resource_rdf_class_path site.host, node.id, dataset.id, resource.id } let(:rdf_class_preview_path) { opendata_dataset_resource_rdf_class_preview_path site.host, node.id, dataset.id, resource.id } let(:column_types_path) { opendata_dataset_resource_column_types_path site.host, node.id, dataset.id, resource.id } let(:rdf_prop_select_path) do routes = Rails.application.routes.url_helpers url = routes.url_for host: "example.com", controller: "opendata/dataset/csv2rdf_settings", action: "rdf_prop_select", site: site.host, cid: node.id, dataset_id: dataset.id, resource_id: resource.id, column_index: 1 url = ::URI.parse(url) url.path end let(:confirmation_path) { opendata_dataset_resource_confirmation_path site.host, node.id, dataset.id, resource.id } let(:show_resource_path) { opendata_dataset_resource_path site.host, node.id, dataset.id, resource.id } it do expect(SS.config.opendata.fuseki["disable"]).to be_truthy visit header_size_path expect(status_code).to eq 200 expect(current_path).to eq header_size_path within "form#item-form" do click_button I18n.t("opendata.button.next") end expect(status_code).to eq 200 expect(current_path).to eq rdf_class_path # クラスのプレビュー画面に寄り道 within "form#item-form" do click_link "ic:定期スケジュール型" end expect(status_code).to eq 200 expect(current_path).to eq rdf_class_preview_path within "body" do click_link "戻る" end expect(status_code).to eq 200 expect(current_path).to eq rdf_class_path rdf_class = Rdf::Class.first within "form#item-form" do choose "item_class_id_#{rdf_class.id}" click_button I18n.t("opendata.button.next") end expect(status_code).to eq 200 expect(current_path).to eq column_types_path # "xsd:integer" を "xsd:decimal" に変更 within "div.csv2rdf-settings-table-container" do click_link "xsd:integer" end expect(status_code).to eq 200 expect(current_path).to eq rdf_prop_select_path within "form#item-form" do choose "item_prop_id_endemicdecimal" click_button "保存" end expect(status_code).to eq 200 expect(current_path).to eq column_types_path within "form#item-form" do click_button I18n.t("opendata.button.next") end expect(status_code).to eq 200 expect(current_path).to eq confirmation_path within "form#item-form" do click_button I18n.t("opendata.button.build") end expect(status_code).to eq 200 expect(current_path).to eq show_resource_path # check for whether ttl file is created and registered. expect { dataset.reload }.to change { dataset.resources.size }.by(1) ttl_resource = dataset.resources.where(format: "TTL").first expect(ttl_resource).not_to be_nil end end describe "convert 2-rows-csv to rdf" do let(:csv_file) { Rails.root.join("spec", "fixtures", "opendata", "shift_jis-3.csv") } let(:resource) { dataset.resources.new(attributes_for(:opendata_resource, license_id: license.id)) } let(:header_size_path) { opendata_dataset_resource_header_size_path site.host, node.id, dataset.id, resource.id } let(:show_resource_path) { opendata_dataset_resource_path site.host, node.id, dataset.id, resource.id } before do Fs::UploadedFile.create_from_file(csv_file, basename: "spec") do |f| resource.in_file = f resource.save! end resource.reload end it do expect(SS.config.opendata.fuseki["disable"]).to be_truthy visit header_size_path expect(status_code).to eq 200 expect(current_path).to eq show_resource_path # acquire that unable to convert to rdf message. within "aside#notice" do expect(page).to have_content(I18n.t('opendata.messages.require_at_least_two_rows')) end end end end
shirasagi/opendata
config/routes/opendata/app/routes.rb
<reponame>shirasagi/opendata SS::Application.routes.draw do Opendata::Initializer concern :deletion do get :delete, on: :member end content "opendata" do resources :app_categories, concerns: :deletion, module: :app resources :search_apps, concerns: :deletion, module: :app resources :apps, concerns: :deletion, module: :app do resources :appfiles, concerns: :deletion do get "file" => "appfiles#download" end end end node "opendata" do get "app_category/" => "public#index", cell: "nodes/app/app_category" get "app_category/rss.xml" => "public#index", cell: "nodes/app/app_category" get "app_category/:name/" => "public#index", cell: "nodes/app/app_category" get "app_category/:name/rss.xml" => "public#rss", cell: "nodes/app/app_category" # get "app_category/:name/areas" => "public#index_areas", cell: "nodes/app/app_category" # get "app_category/:name/tags" => "public#index_tags", cell: "nodes/app/app_category" # get "app_category/:name/licenses" => "public#index_licenses", cell: "nodes/app/app_category" get "app/(index.:format)" => "public#index", cell: "nodes/app/app" get "app/rss.xml" => "public#rss", cell: "nodes/app/app" get "app/areas" => "public#index_areas", cell: "nodes/app/app" get "app/tags" => "public#index_tags", cell: "nodes/app/app" get "app/licenses" => "public#index_licenses", cell: "nodes/app/app" get "app/:app/point.:format" => "public#show_point", cell: "nodes/app/app", format: false post "app/:app/point.:format" => "public#add_point", cell: "nodes/app/app", format: false get "app/:app/point/members.html" => "public#point_members", cell: "nodes/app/app", format: false get "app/:app/ideas/show.:format" => "public#show_ideas", cell: "nodes/app/app", format: false get "app/:app/executed/show.:format" => "public#show_executed", cell: "nodes/app/app", format: false post "app/:app/executed/add.:format" => "public#add_executed", cell: "nodes/app/app", format: false get "app/:app/zip" => "public#download", cell: "nodes/app/app", format: false get "app/:app/appfile/:id/" => "public#index", cell: "nodes/app/appfile" get "app/:app/appfile/:id/content.html" => "public#content", cell: "nodes/app/appfile", format: false get "app/:app/appfile/:id/json.html" => "public#json", cell: "nodes/app/appfile", format: false get "app/:app/appfile/:id/*filename" => "public#download", filename: /.*/, cell: "nodes/app/appfile", format: false get "app/:app/full" => "public#full", cell: "nodes/app/app", format: false get "app/:app/file_index/(*filename)" => "public#app_index", filename: /.*/, cell: "nodes/app/app", format: false get "app/:app/file_text/(*filename)" => "public#text", filename: /.*/, cell: "nodes/app/app", format: false match "search_app/(index.:format)" => "public#index", cell: "nodes/app/search_app", via: [:get, :post] get "search_app/rss.xml" => "public#rss", cell: "nodes/app/search_app" end part "opendata" do get "app" => "public#index", cell: "parts/app/app" end page "opendata" do get "app/:filename.:format" => "public#index", cell: "pages/app/app" end end
shirasagi/opendata
app/helpers/event/event_helper.rb
<filename>app/helpers/event/event_helper.rb<gh_stars>1-10 module Event::EventHelper require "holiday_japan" def t_date(name) t("datetime.prompts.#{name}") end def t_wday(date) t("date.abbr_day_names")[date.wday] end def t_wdays t("date.abbr_day_names") end def event_h1_class(month) %w(jan feb mar apr may jun jul aug sep oct nov dec)[month - 1] end def event_dl_class(date) cls = %w(sun mon tue wed thu fri sat)[date.wday] date.national_holiday? ? "#{cls} holiday" : cls end def event_td_class(date, cdate) cls = event_dl_class(date) cls = "#{cls} today" if date == Time.zone.today if date.month > cdate.month "#{cls} next-month" elsif date.month < cdate.month "#{cls} prev-month" else cls end end def event_category_class(page) page.categories.entries.map { |cate| cate.basename }.join(" ") end def within_one_year?(date) # get current date current = Time.zone.today # manipulate year from current date start_date = current.advance(years: -1) close_date = current.advance(years: 1, month: 1) date.between?(start_date, close_date) end def link_to_monthly(date, opts = {}) year = date.year month = date.month name = opts[:name].present? ? opts[:name] : "#{month}#{t_date('month')}" path = opts[:path].present? ? opts[:path] : @cur_node.try(:url).to_s enable = (opts[:enable] != nil) ? opts[:enable] : true if enable && within_one_year?(date) link_to name , sprintf("#{path}%04d%02d.html", year, month) else name end end def link_to_daily(date, opts = {}) year = date.year month = date.month day = date.day name = opts[:name].present? ? opts[:name] : "#{day}#{t_date('day')}" path = opts[:path].present? ? opts[:path] : @cur_node.try(:url).to_s enable = (opts[:enable] != nil) ? opts[:enable] : true if enable && within_one_year?(date) link_to name, sprintf("#{path}%04d%02d%02d.html", year, month, day) else name end end end
shirasagi/opendata
app/models/concerns/inquiry/addon/release_plan.rb
module Inquiry::Addon module ReleasePlan extend ActiveSupport::Concern extend SS::Addon included do field :release_date, type: DateTime field :close_date, type: DateTime permit_params :release_date, :close_date validate :validate_release_date end module ClassMethods public def public(date = nil) date = Time.zone.now unless date super(date) end end public def public? if (release_date.present? && release_date > Time.zone.now) || (close_date.present? && close_date < Time.zone.now) false else super end end def label(name) if name == :state state = public? ? "public" : "closed" I18n.t("views.options.state.#{state}") else super(name) end end private def validate_release_date self.released ||= release_date if close_date.present? if release_date.present? && release_date >= close_date errors.add :close_date, :greater_than, count: t(:release_date) end end end end end
shirasagi/opendata
app/controllers/opendata/agents/nodes/app/appfile_controller.rb
<gh_stars>1-10 class Opendata::Agents::Nodes::App::AppfileController < ApplicationController include Cms::NodeFilter::View include Opendata::UrlHelper before_action :accept_cors_request before_action :set_app private def set_app @app_path = @cur_path.sub(/\/appfile\/.*/, ".html") @app = Opendata::App.site(@cur_site).public. filename(@app_path). first raise "404" unless @app end public def index redirect_to @app_path end def download @item = @app.appfiles.find_by id: params[:id], filename: params[:filename].force_encoding("utf-8") send_file @item.file.path, type: @item.content_type, filename: @item.filename, disposition: :attachment, x_sendfile: true end def content @cur_node.layout_id = nil @item = @app.appfiles.find_by id: params[:id], format: "CSV" render nothing: true unless @data = @item.parse_csv end def json @cur_node.layout_id = nil @item = @app.appfiles.find_by id: params[:id], format: "JSON" @json = File.read(@item.file.path, :encoding => Encoding::UTF_8) render end end
shirasagi/opendata
app/controllers/rdf/vocabs_controller.rb
<reponame>shirasagi/opendata<filename>app/controllers/rdf/vocabs_controller.rb class Rdf::VocabsController < ApplicationController include Cms::BaseFilter include Cms::CrudFilter helper Opendata::FormHelper model Rdf::Vocab navi_view "cms/main/navi" before_action :set_extra_crumbs, only: [:show, :edit, :update, :delete, :destroy] private def fix_params { cur_site: @cur_site } end def set_crumbs @crumbs << [:"rdf.vocabs", action: :index] end def set_extra_crumbs set_item @crumbs << [@item.labels.preferred_value, action: :show, id: @item] if @item.present? end def save_file temp_file = SS::TempFile.new temp_file.cur_user = @cur_user temp_file.in_file = @params.in_file temp_file.state = "private" temp_file.save! temp_file end def extract_errors(e) if e.respond_to?(:document) e.document.errors.full_messages else [ e.to_s ] end end public def index raise "403" unless @model.allowed?(:read, @cur_user, site: @cur_site, node: @cur_node) @items = @model.site(@cur_site). allow(:read, @cur_user, site: @cur_site). search(params[:s]). order_by(_id: -1). page(params[:page]).per(50) end def import @params = OpenStruct.new return render unless request.post? @params = OpenStruct.new(params.require(:params).permit(:prefix, :order, :owner, :in_file)) @file = save_file @params.in_file.try(:delete) Rdf::VocabImportJob.call_async(@cur_site.host, @params.prefix, @file.id, @params.owner, @params.order) do |job| job.site_id = @cur_site.id end SS::RakeRunner.run_async "job:run", "RAILS_ENV=#{Rails.env}" respond_to do |format| format.html { redirect_to({ action: :index }, { notice: t("rdf.notices.start_import_job") }) } format.json { render json: @params.to_json, status: :created } end rescue => e logger.warn("#{e.class} (#{e.message}):\n #{e.backtrace.join("\n ")}") @params.in_file.try(:delete) @errors = extract_errors(e) respond_to do |format| format.html { render } format.json { render json: @errors, status: :unprocessable_entity } end end end
shirasagi/opendata
app/models/chorg/context.rb
module Chorg::Context attr_reader :cur_site, :cur_user, :adds_group_to_site, :item attr_reader :results, :substituter, :validation_substituter, :delete_group_ids def init_context @results = { "add" => { "success" => 0, "failed" => 0 }, "move" => { "success" => 0, "failed" => 0 }, "unify" => { "success" => 0, "failed" => 0 }, "division" => { "success" => 0, "failed" => 0 }, "delete" => { "success" => 0, "failed" => 0 } } @substituter = Chorg::Substituter.new @validation_substituter = Chorg::Substituter.new @delete_group_ids = [] end def inc_counter(method, type) @results["#{method}"]["#{type}"] += 1 end end
shirasagi/opendata
spec/factories/opendata/member.rb
<reponame>shirasagi/opendata<gh_stars>1-10 FactoryGirl.define do factory :opendata_member, class: Opendata::Member do transient do site nil icon_file nil end site_id { site.present? ? site.id : cms_site.id } name { "#{unique_id}" } email { <EMAIL>" } in_password "<PASSWORD>" in_icon { icon_file.present? ? icon_file : nil } end end
shirasagi/opendata
app/models/cms/site.rb
class Cms::Site include SS::Model::Site include Cms::SitePermission include Cms::Addon::PageSetting include Opendata::Addon::SiteSetting set_permission_name "cms_sites" end
shirasagi/opendata
app/controllers/opendata/agents/nodes/mypage/mypage_controller.rb
class Opendata::Agents::Nodes::Mypage::MypageController < ApplicationController include Cms::NodeFilter::View include Member::LoginFilter include Opendata::MemberFilter helper Opendata::UrlHelper before_action :get_member_notice, only: [:show_notice, :confirm_notice] private def get_member_notice if @cur_member @notice ||= Opendata::MemberNotice.where({site_id: @cur_site.id, member_id: @cur_member.id}).first end end public def index if view_context.dataset_enabled? redirect_to view_context.my_dataset_path elsif view_context.app_enabled? redirect_to view_context.my_app_path elsif view_context.idea_enabled? redirect_to view_context.my_idea_path else redirect_to view_context.my_profile_path end end def show_notice @cur_node.layout = nil end def confirm_notice @cur_node.layout = nil @notice.commented_count = 0 @notice.confirmed = Time.zone.now @notice.save! redirect_to "#{@cur_node.url}notice/show.html" end end
shirasagi/opendata
app/controllers/ads/agents/parts/banner_controller.rb
class Ads::Agents::Parts::BannerController < ApplicationController include Cms::PartFilter::View public def index @node = @cur_part.parent return render nothing: true unless @node cond = {} if @cur_part.with_category == "enabled" if cur_page && cur_page.categories.size > 0 cond.merge! :ads_category_ids.in => cur_page.categories.pluck(:id) elsif cur_node && cur_node.route =~ /^category\// cond.merge! :ads_category_ids.in => [cur_node.id] end end sort = @cur_part.becomes_with_route.sort_hash @random = sort[:random] @items = Ads::Banner.site(@cur_site).node(@node).public(@cur_date). where(cond). order_by(sort) end end
shirasagi/opendata
app/models/ckan/node.rb
<reponame>shirasagi/opendata module Ckan::Node class Page include Cms::Model::Node include Cms::Addon::NodeSetting include Cms::Addon::Meta include Cms::Addon::PageList include Ckan::Addon::Server include Cms::Addon::Release include Cms::Addon::GroupPermission include History::Addon::Backup default_scope ->{ where(route: "ckan/page") } end end
shirasagi/opendata
lib/voice/command.rb
<gh_stars>1-10 class Voice::Command class << self public def run_with_logging(cmd, prompt) require "open3" Rails.logger.debug("popen3: #{cmd}") stdout, stderr, status = Open3.capture3(cmd) Rails.logger.debug("[#{prompt} stdout] #{stdout}") if stdout.present? Rails.logger.info("[#{prompt} stderr] #{stderr}") if stderr.present? status end end end
shirasagi/opendata
app/models/concerns/contact/addon/page.rb
<gh_stars>1-10 module Contact::Addon module Page extend ActiveSupport::Concern extend SS::Addon included do field :contact_state, type: String field :contact_charge, type: String field :contact_tel, type: String field :contact_fax, type: String field :contact_email, type: String belongs_to :contact_group, class_name: "SS::Group" permit_params :contact_state, :contact_group_id, :contact_charge permit_params :contact_tel, :contact_fax, :contact_email end public def contact_state_options [ [I18n.t('views.options.state.show'), 'show'], [I18n.t('views.options.state.hide'), 'hide'], ] end def contact_present? [contact_charge, contact_tel, contact_fax, contact_email ].map(&:present?).any? end end end
shirasagi/opendata
app/models/opendata/dataset_group.rb
<gh_stars>1-10 class Opendata::DatasetGroup include SS::Document include SS::Reference::User include SS::Reference::Site include Cms::Addon::Release include Cms::Addon::GroupPermission include Opendata::Addon::Category set_permission_name :opendata_datasets seqid :id field :state, type: String, default: "public" field :name, type: String field :order, type: Integer permit_params :state, :name, :order, file_ids: [] validates :state, presence: true validates :name, presence: true, length: { maximum: 80 } validates :category_ids, presence: true def state_options [[I18n.t("opendata.state_options.public"), "public"], [I18n.t("opendata.state_options.closed"), "closed"]] end class << self public def public where(state: "public") end def search(params) criteria = self.where({}) return criteria if params.blank? if params[:name].present? words = params[:name].split(/[\s ]+/).uniq.compact.map {|w| /\Q#{Regexp.escape(w)}\E/ } criteria = criteria.all_in name: words end if params[:category_id].present? criteria = criteria.where category_ids: params[:category_id].to_i end criteria end end end
shirasagi/opendata
app/models/workflow/route.rb
class Workflow::Route include Workflow::Model::Route include Cms::SitePermission set_permission_name "cms_users", :edit scope :site, ->(site) { self.in(group_ids: Cms::Group.site(site).pluck(:id)) } validate :validate_groups class << self public def route_options(user) ret = [ [ t("my_group"), "my_group" ] ] group_ids = user.group_ids.to_a Workflow::Route.where(:group_ids.in => group_ids).each do |route| ret << [ route.name, route.id ] end ret end end private def validate_groups self.errors.add :group_ids, :blank if groups.blank? end end
shirasagi/opendata
app/models/concerns/cms/model/member.rb
module Cms::Model::Member extend ActiveSupport::Concern extend SS::Translation include SS::Document include SS::Reference::Site include Cms::SitePermission attr_accessor :in_password OAUTH_PROVIDER_TWITTER = 'twitter'.freeze OAUTH_PROVIDER_FACEBOOK = 'facebook'.freeze OAUTH_PROVIDER_YAHOOJP = 'yahoojp'.freeze OAUTH_PROVIDER_GOOGLE_OAUTH2 = 'google_oauth2'.freeze OAUTH_PROVIDER_GITHUB = 'github'.freeze OAUTH_PROVIDERS = [ OAUTH_PROVIDER_TWITTER, OAUTH_PROVIDER_FACEBOOK, OAUTH_PROVIDER_YAHOOJP, OAUTH_PROVIDER_GOOGLE_OAUTH2, OAUTH_PROVIDER_GITHUB ].freeze included do store_in collection: "cms_members" set_permission_name :cms_users, :edit seqid :id field :name, type: String field :email, type: String, metadata: { form: :email } field :password, type: String field :oauth_type, type: String field :oauth_id, type: String field :oauth_token, type: String field :site_email, type: String field :last_loggedin, type: DateTime permit_params :name, :email, :password, :in_password validates :name, presence: true, length: { maximum: 40 } validates :email, email: true, length: { maximum: 80 } validates :email, uniqueness: { scope: :site_id }, presence: true, if: ->{ oauth_type.blank? } validates :password, presence: true, if: ->{ oauth_type.blank? } before_validation :encrypt_password, if: ->{ in_password.present? } before_save :set_site_email, if: ->{ email.present? } end private def set_site_email self.site_email = "#{site_id}_#{email}" end public def encrypt_password self.password = SS::Crypt.crypt(in_password) end end
shirasagi/opendata
app/helpers/cms/path_helper.rb
module Cms::PathHelper public def cms_mobile_preview_path(params = {}) if params[:path] params[:path] = ::File.join(SS.config.mobile.location, params[:path]) params[:path].sub!(/^\/+/, "") end cms_preview_path(params) end end
shirasagi/opendata
app/models/concerns/opendata/addon/my_app_list.rb
<filename>app/models/concerns/opendata/addon/my_app_list.rb module Opendata::Addon::MyAppList extend SS::Addon extend ActiveSupport::Concern include Cms::Addon::PageList public def template_variable_get(item, name) if name.start_with?('app_') if name == 'app_name' ERB::Util.html_escape item.name elsif name == 'app_url' ERB::Util.html_escape "#{self.url}#{item.id}/" elsif name == 'app_updated' I18n.l item.updated, format: I18n.t("opendata.labels.updated") elsif name =~ /^app_updated\.(.+)$/ I18n.l item.updated, format: $1 elsif name == 'app_state' ERB::Util.html_escape(item.label :status) elsif name == 'app_point' ERB::Util.html_escape(item.point.to_i.to_s) else false end else super end end end