Lawrence  Lesch

Lawrence Lesch

1662360604

Palette.js: Script for Generating Colour Palettes For Use with Graphs

Colour Palette Generator

The palette.js script allows to generate palette colours and was intended for use with graphs, charts and cartography. In default setup, it contains Paul Tol's and ColorBrewer palettes specifically designed for that purpose. The library includes several qualitative, sequential and diverging colour schemes

Some of the included palettes have a limited number of colours, but others use a colour generation functions and can potentially create a whole spectrum of colours.

There is an interactive demo of the library if you wish to see what it can do.

Naming

The basic two concepts in palette.js library are schemes and palettes. It is important to understand what they are so as to understand the API of the library.

A palette is a sequence of colours and it is represented by an array of colours encoded as “RRGGBB” strings. Palette has a fixed size or number of colours in it. For example, the following code defines a 8-colour palette which is a sequence of base colours of the Solarized palette:

var sol_base = ['002b36', '073642', '586e75', '657b83',
                '839496', '93a1a1', 'eee8d5', 'fdf6e3'];

A scheme is a set of colour palettes and it is represented by a function with some additional properties and methods (i.e. it can be used as an object). In simplest cases, scheme will be used to generate a palette of desired size. For example, if hsv_rainbow is an HSV rainbow scheme, the following code generates a 6-colour palette based on the scheme:

var hsv6 = hsv_rainbow(6);

Library quick start

The simplest way to access the library is by calling palette function. It takes two required arguments: A name of a colour scheme and size of the palette. For example to generate a 10-colour palette one would invoke:

var seq = palette('tol-sq', 10);

tol-sq is a name for Paul Tol's sequential scheme. In addition to names of schemes the function can also take group names or a list of palette names. For example:

var seq = palette('sequential', 10);
var cbf = palette('sequential-cbf', 10);

will take the first available sequential colour scheme and generate 10-colour palette storing it in seq. The second line does the same except it limits the palettes to only those that are colour blind friendly.

The argument can also be a list of colour schemes as in:

var div = palette(['tol', 'qualitative'], 10);

Here, div will be assigned an array of colours from Paul Tol's qualitative scheme unless it is not available in which case the first available qualitative colour scheme will be used.

Another use of a list of schemes or group names is a third optional argument to the palette function -- the index for the scheme to use. When specified, not the first one, but the given scheme will be used (indexed from zero). This can be used to generate distinct colour palettes for various types of data.

var pal_for_queries = palette(['sequential'], 10, 0);
var pal_for_errors = palette(['sequential'], 10, 1);
var pal_for_latency = palette(['sequential'], 10, 2);

With the above code, three separate 10-colour palettes will be generated each for different kind of data.

If no schemes matched specified name(s), palette function will return null.

For a full reference please see the source code.

Note on colour blindness

A palette can be colour blind friendly, or CBF, meaning that colours in it are distinguishable by a colour blind person. Scheme can also be colour blind friendly (for example all Paul Tol's schemes are), but more often only some of the palettes in given scheme are (for example a 4-colour palette based on ColorBrewer Paired scheme is CBF, but bigger palettes aren't).

The demo page contains code for colour blindness simulation mode.

Download Details:

Author: Google
Source Code: https://github.com/google/palette.js 
License: Unknown and 3 other licenses found

#javascript #script #graphs #charts 

Palette.js: Script for Generating Colour Palettes For Use with Graphs
Mike  Kozey

Mike Kozey

1661396760

Dcli_scripts: A Collection Of Cli Scripts That Do Odd Jobs for Me

An eclectic collection of CLI scripts that help me manage my dev environment.

Some of my favourites:

commands

commanddescriptionExample
dportfinds what process has a tcp port open.dport 80
cleancleans out stale docker and git files and highlights large directories.clean
dmailhoginstalls and starts/stops mailhog.dmailhog | dmailhog --shutdown
dmysqlBackup/Restore and connects you to a mysql cli pulling settings (username/password) from a per database local settings file.dmysql mydb backup | dmysql mydb restore <path>
dwhichan improved which command that also highlights invalid paths 
gitgcruns garbage collection on all your git projects. 
hogfinds system resource hogs. 
ipaddrshows the ip address on your local machine. 
docker_pushbuilds a docker file and pushes it to docker.hub. 
kill_tomcatkills any java tomcat instances. 
pub_get_allrecursively runs dart pub get 
hex_dumpdumps the contents of a file in hex and ascii. 
find_textFind a file that contains the given text 

dfind

Recursively searches for a file with a matching glob pattern

Example

dfind '*.dart'

dport

Prints out the name of the process that is listening on the passed tcp port.

Example

dport 80

dmysql

Allows you to store the username/password for a mysql database in a configure file and then run a number of mysql commands against that database withouth continuously re-entering the username/password.

Example

To create a configuration file for a given database run:

dmysql config <dbname>
 host: <enter host>
 port: <enter port>
 user: <enter user>
 password: <enter password>

Once you have created a config you can run any of the following commands.

backup

Backup the database via:

dmysql backup <path to backup file>

restore

Restore a database

WARNING: this will delete you existing schema.

dmysql restore <path to backup file>

cli

Connect to the mysql cli

dmysql cli <database name>

find_text

List each file that matches the pass text. The search is run recursively from the current directory.

Example

Search all dart files for a line that contains 'final String'.

find_text 'final String' '*.dart'

apis

The dcli_scripts package also includes some handy apis.

dockerPublish

Designed to build and publish a docker image which contains a Dart project built with dcli.

The api assumes that you are cloning a git repo into your docker image and that you need to rebuild you image each time the git repo changes.

The api allows you to rebuild you docker image from the clone step rather than having to rebuild the entire docker image.

Your docker file should have the following line just before the package's git clone line.

RUN mkdir -p /BUILD_TOKEN/

We will run a:

  • dcli pack
  • git add *
  • git commit -m 'release'
  • git push

You need to provide the path to your dockerfile via [pathToDockerFile].

The docker tag will be generated from your pubspec.yaml and the [repository] argument in the form:

<repository>/<pubspec.name>:<pubspec.version>

So if you pass in 'noojee' as the repository and your package is dcli then you might get:

noojee/dcli:1.16.0

If you pass the [clean] = true then the image will be rebuilt from scratch.

If you pass the [fresh] = true then the Docker image will be rebuilt from the line that contains BUILD_TOKEN.

We search for the BUILD_TOKEN line in your docker file and update the token UUID. This will cause the docker image to be rebuilt from the BUILD_TOKEN line. This can be used if you need to re-clone a git repo (or any similar action).

By default the image will be pushed to docker hub unless you pass [push] = false.

By default we ask you to confirm the build process. Pass [confirm] = false to skip the question.

If you pass [pack] = true then the 'dcli pack' command will be run and any changes committed to your git repo before the build starts. If you pass [pack] = true then [fresh] will automatically be set to true to force a fresh git clone.

Here is an example Dockerfile that builds for an arm64 target ( I use this for raspberry pi testing.)

# used to build the dart exes in a docker arm image
# trying to build dart execs on a pi is just to slow
# hence we do the build in a docker image on our
# development box.

# docker image instructions came from.
# https://hub.docker.com/r/balenalib/raspberrypi4-64-debian


# FROM balenalib/raspberrypi4-64-ubuntu:latest
FROM balenalib/raspberrypi4-64-ubuntu-openjdk:latest
# replace this with your application


# install build tools
# && apt install --no-install-recommends -y openjdk-8-jdk-headless maven git \

RUN apt update \
    && apt install --no-install-recommends -y \
    wget \
    git \
    maven \
    unzip \
    && rm -rf /var/lib/apt/lists/*

RUN wget https://storage.googleapis.com/dart-archive/channels/be/raw/latest/sdk/dartsdk-linux-arm64-release.zip --output-document=dart.zip
RUN unzip dart.zip

# add dart to the path.
ENV PATH="$PATH:/dart-sdk/bin"


RUN mkdir -p /BUILD_TOKEN/
RUN git clone https://github.com/bsutton/IrrigationForPi.git



WORKDIR IrrigationForPi/build_tools

RUN dart pub get
RUN dart bin/pig_build.dart --current --no-tools --no-full

Use this package as an executable

Install it

You can install the package from the command line:

dart pub global activate dcli_scripts

Use it

The package has the following executables:

$ add_gnome_launcher
$ artifactory
$ bobthefish
$ certbot_renew
$ clean
$ dcompress
$ dcopydir
$ denv
$ dfind
$ dmailhog
$ dmysql
$ dnsflush
$ docker_dcli
$ docker_push
$ downit
$ dpath
$ dport
$ dreplace
$ dsetver
$ dsort
$ dvirtualbox
$ dwc
$ dwhich
$ dzfs_clean
$ eclipse_launcher
$ find_old_dart_packages
$ find_text
$ gitadd_team_to_repository
$ gitcreation_date
$ gitgc
$ gitsyncfork
$ gituncommited
$ gitupdate_remote
$ hexdump
$ hog
$ install_flutter
$ ipaddr
$ kill_tomcat
$ pub_get_all

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add dcli_scripts

With Flutter:

 $ flutter pub add dcli_scripts

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  dcli_scripts: ^1.3.0

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:dcli_scripts/dcli_scripts.dart';

Download Details:

Author: onepub-dev
Source Code: https://github.com/onepub-dev/dcli_scripts 
License: MIT license

#flutter #dart #cli #script 

Dcli_scripts: A Collection Of Cli Scripts That Do Odd Jobs for Me

Unitful Quantity-valued Functions in Your Integrals

UnitfulIntegration

This package enables integration of physical quantity-valued functions, using the Quantity types implemented in Unitful.jl.

This package currently supports QuadGK.jl, which was originally in Julia Base. We do not support QuadGK as implemented in Julia 0.5. To use this package with Julia 0.5, you need to install the QuadGK package and qualify all invocations of QuadGK functions with the module name (e.g. import QuadGK; QuadGK.quadgk(...)).

PRs for other integration packages are welcome.

Code

*.jl.cov
*.jl.*.cov
*.jl.mem
# Documentation: http://docs.travis-ci.com/user/languages/julia/
language: julia
os:
  - linux
julia:
  - 0.7
  - 1.0
  - nightly
notifications:
  email: false
# uncomment the following lines to override the default test script
#script:
#  - if [[ -a .git/shallow ]]; then git fetch --unshallow; fi
#  - julia -e 'Pkg.clone(pwd()); Pkg.build("UnitfulIntegration"); Pkg.test("UnitfulIntegration"; coverage=true)'
after_success:
  # push coverage results to Coveralls
  - julia -e 'cd(Pkg.dir("UnitfulIntegration")); Pkg.add("Coverage"); using Coverage; Coveralls.submit(Coveralls.process_folder())'
  # push coverage results to Codecov
  - julia -e 'cd(Pkg.dir("UnitfulIntegration")); Pkg.add("Coverage"); using Coverage; Codecov.submit(Codecov.process_folder())'

Download Details:

Author: PainterQubits
Source Code: https://github.com/PainterQubits/UnitfulIntegration.jl 
License: View license

#julia #unit 

Unitful Quantity-valued Functions in Your Integrals

UnitfulPlots.jl: Plots with Unit Labels, Automatically

UnitfulPlots

Enables automatic labeling of units on axes of plots generated with Plots.jl. The unitful quantities are created in the first place using Unitful.jl.

To use, simply type using UnitfulPlots in Julia 0.7 or higher and plot arrays of quantities as you usually would.

This package is experimental, please report unexpected behavior or submit pull requests.

Code

*.jl.cov
*.jl.*.cov
*.jl.mem
# Documentation: http://docs.travis-ci.com/user/languages/julia/
language: julia
os:
  - linux
  - osx
julia:
  - release
  - nightly
notifications:
  email: false
# uncomment the following lines to override the default test script
#script:
#  - if [[ -a .git/shallow ]]; then git fetch --unshallow; fi
#  - julia -e 'Pkg.clone(pwd()); Pkg.build("UnitfulPlots"); Pkg.test("UnitfulPlots"; coverage=true)'
after_success:
  # push coverage results to Coveralls
  - julia -e 'cd(Pkg.dir("UnitfulPlots")); Pkg.add("Coverage"); using Coverage; Coveralls.submit(Coveralls.process_folder())'
  # push coverage results to Codecov
  - julia -e 'cd(Pkg.dir("UnitfulPlots")); Pkg.add("Coverage"); using Coverage; Codecov.submit(Codecov.process_folder())'

Download Details:

Author: PainterQubits
Source Code: https://github.com/PainterQubits/UnitfulPlots.jl 
License: View license

#julia #unit 

UnitfulPlots.jl: Plots with Unit Labels, Automatically
Dexter  Goodwin

Dexter Goodwin

1661168460

Ackee-lighthouse: Send Lighthouse Reports to Ackee

ackee-lighthouse

A script that runs continuously thanks to GitHub Actions and sends Lighthouse reports the Ackee.

🤗 Usage

1. Install dependencies

ackee-lighthouse dependents on …

Make sure to install and update all dependencies before you continue. The installation instructions for the individual dependencies can be found on the linked websites.

2. Create the configuration

Pull the project and configure ackee-lighthouse using environment variables or create a .env file in the root of the project to store all variables in one file.

Examples:

ACKEE_ENDPOINT=https://ackee.example.com/api
ACKEE_EVENT_ID=a26932b8-a088-4fc1-b723-c3ea5b9ba9e4
URL=https://a.example.com
ACKEE_ENDPOINT=https://ackee.example.com/api
ACKEE_EVENT_ID=a26932b8-a088-4fc1-b723-c3ea5b9ba9e4,6bad9a10-ed63-447b-b026-086b80da15d2
URL=https://a.example.com,https://b.example.com
AUDIT=speed-index.numericValue

3. Install ackee-lighthouse

Install all required dependencies.

yarn install

4. Run ackee-lighthouse

ackee-lighthouse will create a Lighthouse report for every URL specified in the environment. The AUDIT option must be a dot path that selects a single value from the Lighthouse report. It defaults to speed-index.numericValue, which will report the speed index as a numeric value (in milliseconds). ackee-lighthouse will send the selected value to the specified Ackee event.

Multiple URLs are handled so that the first URL uses the first event id, the second URL uses the second event id, and so on.

yarn start

Miscellaneous

Donate

I am working hard on continuously developing and maintaining Ackee. Please consider making a donation to keep the project going strong and me motivated.

Links

Download Details:

Author: Electerious
Source Code: https://github.com/electerious/ackee-lighthouse 
License: MIT license

#javascript #send #script 

Ackee-lighthouse: Send Lighthouse Reports to Ackee

BuildExecutable.jl: Build A Standalone Executables From A Julia Script

BuildExecutable

Builds an executable that doesn't require any julia source code. The user needs to provide a julia script that contains a function main(), taking no argument, which will be run when executing the produced executable. An executable can be produced by using the build_executable function

using BuildExecutable
build_executable(exename, script, targetdir, "native")

Note on packages:

Even if the script contains using statements, exported functions will not be available in main(). Full qualification of names is required. It's suggested to replace using statements with import statements to produce a consistent result between running main() in the REPL and running the executable.

If packages with binary dependencies is used the produced executable will not function properly.

Note on portability

The executable produced by build_executable is known to be portable across Windows computers, and OS X, but not on Linux. To increase the portablity use an older cpu_target target as "core2" instead of "native".

Download Details:

Author: dhoegh
Source Code: https://github.com/dhoegh/BuildExecutable.jl 
License: View license

#julia #script 

BuildExecutable.jl: Build A Standalone Executables From A Julia Script
Monty  Boehm

Monty Boehm

1660224900

Progressive Alignment Scripts for Protein Sequences

ProgressiveAligner

This package contains progressive alignment tool for protein sequences written in Julia language.

Builds phylogenetic tree with neighbour joining, UPGMA or WPGMA algorithm, then aligns protein sequences by their profiles.

Usage examples currently can be found in test folder.

Typical usage pipeline

call methods from DataReader submodule and read data from files.

One way to get protein sequences - to read them from file:

sequences = readSequences(dirname(@__FILE__()) * "/../data/input_test_sequences.faa")

After this call, sequences is an Array of FastaRecord objects. FastaRecord object can also be created directly, from description and protein sequence string:

fasta_record  = FastaRecord("test string1", "ACGT")

Alignment algorithm uses alignment score matrix to score sequences; this matrix can be loaded from alignment matrix file, which can be loaded from NCBI ftp.

matrix = readMatrix(dirname(@__FILE__()) * "/../data/blosum62.txt")

Convert and prepare data.

Alignment algorithm don't use FastaRecord objects directly. It converts protein strings data to Profile objects, then merges these objects with different tree building methods to one Profile, which represents multiple alignment and can be converted to Array of FastaRecord objects with gaps.

First step is to incorporate FastaRecords or strings to Array of Profiles:

strToProfiles(strings :: Vector{FastaRecord}) = [Profile{Float64}(record.sequence, record.description) :: Profile{Float64} for record in strings]

profiles = strToProfiles(sequences)

For collection of strings, profile array creation can be done in similar way:

start_vertices2 = [Profile{Float64}(str)::Profile{Float64} for str in
    [
      "CAP",
      "CAPT",
      "APT",
      "PPT"
      ]]

Second step is to set current scoring matrix. This can be done via call

ProfileAligner.setScoringMatrix(score_matrix)

Define score and merge functions:

function scoreFunc(p1 :: Profile{Float64}, p2 :: Profile{Float64})
  ProfileAligner.scoreprofiles(p1, p2)
end

function mergeFunc(p1 :: Profile{Float64}, p2 :: Profile{Float64})
  ProfileAligner.align(p1, p2)
end

Score function returns best alignment score for given pair of profiles. Merge function returns resulting profile object, which can be build by best-scored alignment. The main difference between these two methods - first one can be be computed faster and can consume less memory.

Currently there is default implementation for both of these methods in ProfileAligner submodule (corresponding methods are shown in previous code example), which uses score matrix, set by setScoringMatrix call, to select best-scored profile alignment.

Select one of tree-based methods to perform multiple alignment.

Currently 3 clustering algorithms are implemented - NeighbourJoining, UPGMA, WPGMA. They got similar signature and can be called like that:

njResult = NeighbourJoining(profiles, scoreFunc, mergeFunc)
wpgmaResult = WPGMA(profiles, scoreFunc, mergeFunc)
upgmaResult = UPGMA(profiles, scoreFunc, mergeFunc)

The result of each of these calls is a single Profile object, which represents multiple alignment.

Convert alignment result to readable way. Save results to file.

ProfileAligner submodule provides utility method getstrings, which converts Profile representation back to array of FastaRecord objects (probably with gaps).

getstrings(result)

There is also utility submodule DataWriter, which can be used to save resulting multiple sequence alignment to .fasta-like file.

writeSequences(output_file, getstrings(result))

First parameter should contain file name to save these records.

There is no differences in file format from typical .fasta, except one - in resulting sequence alignment, each string can contain gaps, represented by '-' symbol. Descriptions are kept to make it possible to find where aligned string came from (and we know that clustering algorithms mix input nodes and can change their order).

Download Details:

Author: latticetower
Source Code: https://github.com/latticetower/ProgressiveAligner.jl 
License: View license

#julia #script 

Progressive Alignment Scripts for Protein Sequences

Grape Roar: Use Roar with Grape in Ruby

Grape::Roar   

Use Roar with Grape.

Demo

The grape-with-roar project deployed here on heroku.

Installation

Add the grape, roar and grape-roar gems to Gemfile.

gem 'grape'
gem 'roar'
gem 'grape-roar'

If you're upgrading from an older version of this gem, please see UPGRADING.

Usage

Tell your API to use Grape::Formatter::Roar

class API < Grape::API
  format :json
  formatter :json, Grape::Formatter::Roar
end

Use Grape's Present

Include Grape::Roar::Representer into a representer module after any Roar mixins, then use Grape's present keyword.

module ProductRepresenter
  include Roar::JSON
  include Roar::Hypermedia
  include Grape::Roar::Representer

  property :title
  property :id
end
get 'product/:id' do
  present Product.find(params[:id]), with: ProductRepresenter
end

Presenting collections works the same way. The following example returns an embedded set of products in the HAL Hypermedia format.

module ProductsRepresenter
  include Roar::JSON::HAL
  include Roar::Hypermedia
  include Grape::Roar::Representer

  collection :entries, extend: ProductRepresenter, as: :products, embedded: true
end
get 'products' do
  present Product.all, with: ProductsRepresenter
end

Accessing the Request Inside a Representer

The formatter invokes to_json on presented objects and provides access to the requesting environment via the env option. The following example renders a full request URL in a representer.

module ProductRepresenter
  include Roar::JSON
  include Roar::Hypermedia
  include Grape::Roar::Representer

  link :self do |opts|
    request = Grape::Request.new(opts[:env])
    "#{request.url}"
  end
end

Decorators

If you prefer to use a decorator class instead of modules.

class ProductRepresenter < Grape::Roar::Decorator
  include Roar::JSON
  include Roar::Hypermedia

  link :self do |opts|
    "#{request(opts).url}/#{represented.id}"
  end

  private

  def request(opts)
    Grape::Request.new(opts[:env])
  end
end
get 'products' do
  present Product.all, with: ProductsRepresenter
end

Relation Extensions

If you use either ActiveRecord or Mongoid, you can use the Grape::Roar::Extensions::Relations DSL to expose the relationships in between your models as a HAL response. The DSL methods used are the same regardless of what your ORM/ODM is, as long as there exists an adapter for it.

Designing Representers

Arguments passed to #relation are forwarded to roar. Single member relations (e.g. belongs_to) are represented using #property, collections are represented using #collection; arguments provided to #relation will be passed through these methods (i.e. additional arguments roar and representable accept).

A default base URI is constructed from a Grape::Request by concatenating the #base_url and #script_name properties. The resource path is extracted from the name of the relation.

Otherwise, the extensions attempt to look up the correct representer module/class for the objects (e.g. we infer the extend argument). You can always specify the correct representer to use on your own.

Example Models

class Item < ActiveRecord::Base
  belongs_to :cart
end

class Cart < ActiveRecord::Base
  has_many :items  
end

Example Representers

class ItemEntity < Grape::Roar::Decorator
  include Roar::JSON
  include Roar::JSON::HAL
  include Roar::Hypermedia

  include Grape::Roar::Extensions::Relations

  # Cart will be presented under the _embedded key
  relation :belongs_to, :cart, embedded: true

  link_self
end

class CartEntity < Grape::Roar::Decorator
  include Roar::JSON
  include Roar::JSON::HAL
  include Roar::Hypermedia

  include Grape::Roar::Extensions::Relations

  # Items will be presented under the _links key
  relation :has_many, :items, embedded: false

  link_self
end

Although this example uses Grape::Roar::Decorator, you can also use a module as show in prior examples above. If doing so, you no longer have to mix in Grape::Roar::Representer.

Example Item

{
    "_embedded": {
        "cart": {
            "_links": {
                "self": {
                    "href": "http://example.org/carts/1"
                },
                "items": [{
                    "href": "http://example.org/items/1"
                }]
            }
        }
    },
    "_links": {
        "self": {
            "href": "http://example.org/items/1"
        }
    }
}

Example Cart

{
    "_links": {
        "self": {
            "href": "http://example.org/carts/1"
        },
        "items": [{
            "href": "http://example.org/items/1"
        }, {
            "href": "http://example.org/items/2"
        }, {
            "href": "http://example.org/items/3"
        }, {
            "href": "http://example.org/items/4"
        }, {
            "href": "http://example.org/items/5"
        }]
    }
}

Errors

Should you incorrectly describe a relationship (e.g. you specify has_one but your model specifies has_many), an exception will be raised to notify you of the mismatch:

Grape::Roar::Extensions::Relations::Exceptions::InvalidRelationError:
  Expected Mongoid::Relations::Referenced::One, got Mongoid::Relations::Referenced::Many!

Change how URLs are presented

The opts hash below is the same one as shown in prior examples.

Override base URI mappings

class BarEntity < Grape::Roar::Decorator
  include Roar::JSON
  include Roar::JSON::HAL
  include Roar::Hypermedia

  include Grape::Roar::Extensions::Relations

  # This is our default implementation
  map_base_url do |opts|
    request = Grape::Request.new(opts[:env])
    "#{request.base_url}#{request.script_name}"
  end

  relation :has_many, :bars, embedded: false
end

Override resource URI mappings

class BarEntity < Grape::Roar::Decorator
  include Roar::JSON
  include Roar::JSON::HAL
  include Roar::Hypermedia

  include Grape::Roar::Extensions::Relations

  # This is our default implementation
  map_resource_path do |_opts, object, relation_name|
    "#{relation_name}/#{object.id}"
  end

  relation :has_many, :bars, embedded: false
end

Designing Adapters

If you have custom domain objects, you can create an adapter to make your models compatible with the DSL methods. Below is an example of the ActiveRecord adapter.

Example: ActiveRecord Adapter

module Extensions
  module RelationalModels
    module Adapter
      class ActiveRecord < Base
        include Validations::ActiveRecord

        # We map your domain object to the correct adapter
        # during runtime.
        valid_for { |klass| klass < ::ActiveRecord::Base }

        def collection_methods
          @collection_methods ||= %i(has_many has_and_belongs_to_many)
        end

        def name_for_represented(represented)
          klass_name = case represented
                       when ::ActiveRecord::Relation
                         represented.klass.name
                       else
                         represented.class.name
                       end
          klass_name.demodulize.pluralize.downcase
        end

        def single_entity_methods
          @single_entity_methods ||= %i(has_one belongs_to)
        end
      end
    end
  end
end

Validations

Errors are handled by creating methods corresponding to those in collection_methods and single_entity_methods. For example, this is the validator for belongs_to:

module ActiveRecord
  include Validations::Misc

  def belongs_to_valid?(relation)
    relation = klass.reflections[relation]

    return true if relation.is_a?(
      ::ActiveRecord::Reflection::BelongsToReflection
    )

    # Provided by Validations::Misc
    invalid_relation(
      ::ActiveRecord::Reflection::BelongsToReflection,
      relation.class
    )
  end
end

After writing your validation methods, just mix them into your adapter. You can choose to not write validation methods; they are only invoked if your adapter responds to them.

Contributing

See CONTRIBUTING.

Copyright and License

MIT License, see LICENSE for details.

(c) 2012-2014 Daniel Doubrovkine & Contributors, Artsy


Author:  ruby-grape
Source code: https://github.com/ruby-grape/grape-roar
License: MIT license

#ruby #ruby-on-rails 

Grape Roar: Use Roar with Grape in Ruby