Skip to content

Instantly share code, notes, and snippets.

@cveneziani
Last active March 12, 2021 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cveneziani/0720653efbac6dc45e3ed054847c0e56 to your computer and use it in GitHub Desktop.
Save cveneziani/0720653efbac6dc45e3ed054847c0e56 to your computer and use it in GitHub Desktop.
Snippets

Snippets

Simple Form - Custom dyamic radio button labels

<%= simple_form_for :search, url: chatrooms_path, method: :get do |f| %>
  <%= f.input :tag,
      collection: ["truc", "bidule", "machin"],
      as: :check_boxes,
      multiple: true,
      checked: params[:search].present? ? params[:search][:tag] : [],
      label_method: lambda { |tag| render 'chatrooms/tag_label', tag: tag },
      wrapper_tag: :div,
      wrapper_class: "tags-container" %>
  <%= f.submit "Filtrer", class: "btn btn-primary" %>
<% end %>

Elastic Search & Clever Cloud

if Rails.env.production?
  Elasticsearch::Client.new hosts: [
    {  
      host: ENV['ES_ADDON_HOST'],
      port: '443',
      user: ENV['ES_ADDON_USER'],
      password: ENV['ES_ADDON_PASSWORD'],
      scheme: 'https'
    }
  ]
end

PDF Generation

def generate_invoice_pdf_file
  pdf_html = ApplicationController.render(
    assigns: {
      invoice: @invoice,
      format:  'pdf'
    },
    template: 'invoices/show',
    layout:   'pdf'
  )

  pdf = WickedPdf.new.pdf_from_string(pdf_html,
    page_size:   'A4',
    orientation: 'portrait',
    lowquality:   true,
    zoom:         0.9,
    dpi:          75
  )

  tempfile = Tempfile.new("invoice-#{@invoice.id}.pdf")

  File.open(tempfile.path, 'wb') do |file|
    file << pdf
  end

  tempfile.close

  return tempfile.path
end

Mapbox once rendered

function onMapRenderComplete(map, fn) {
  if (map.loaded()) { return process.nextTick(fn); }
  map.once('render', () => onMapRenderComplete(map, fn));
}

onMapRenderComplete(map, function () {
  startTimer();
});

Mapbox drawroute

https://github.com/fredech/time_to_surf/blob/151b94442ea86ec0a52fe67d535eb6731aea9b3f/app/javascript/plugins/init_mapbox_show.js

import mapboxgl from 'mapbox-gl';

const initMapboxShow = () => {
  const fitMapToMarkers = (map, markers) => { ... };

  // create a function to make a directions request
  function drawRoute(start, end) {
    // make directions request using cycling profile
    var url = `https://api.mapbox.com/directions/v5/mapbox/driving/${start[0]},${start[1]};${end[0]},${end[1]}?steps=true&geometries=geojson&access_token=${mapboxgl.accessToken}`;

    // make an XHR request https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
    var req = new XMLHttpRequest();
    req.responseType = 'json';
    req.open('GET', url, true);
    req.onload  = function() {
      var data = req.response.routes[0];
      console.log(data.duration)

      // display itinerary duration
      var duration = parseInt(data.duration / 60);
      var distance = parseInt(data.distance / 1000);

      // draw route
      var route = data.geometry.coordinates;
      var geojson = {
        "type": "Feature",
        "properties": {},
        "geometry": {
          "type": "LineString",
          "coordinates": route
        }
      };

      map.addLayer({
        "id": "route",
        "type": "line",
        "source": {
          "type": "geojson",
          "data": {
            "type": "Feature",
            "properties": {},
            "geometry": {
              "type": "LineString",
              "coordinates": geojson
            }
          }
        },
        "layout": {
          "line-join": "round",
          "line-cap": "round"
        },
        "paint": {
          "line-color": "#3887be",
          "line-width": 5,
          "line-opacity": 0.75
        }
      });

      map.getSource('route').setData(geojson);
    };

    req.send();
  };

  const mapElement = document.getElementById('map_show');
  const markers = JSON.parse(mapElement.dataset.markers);
  const start = [markers[0].lng, markers[0].lat];
  const end   = [markers[1].lng, markers[1].lat];

  mapboxgl.accessToken = mapElement.dataset.mapboxApiKey;
  
  var map = new mapboxgl.Map({
    container: 'map_show', // container id
    style: 'mapbox://styles/mapbox/streets-v11', //stylesheet location
    center: start, // starting position
    zoom: 12, // starting zoom
  });

  /// Markers
  markers.forEach((marker) => {
    const element = document.createElement('div');
    element.className = 'marker';
    element.style.backgroundImage = `url('${marker.image_url}')`;
    element.style.backgroundSize = 'contain';
    element.style.width = '40px';
    element.style.height = '40px';

    const popup = new mapboxgl.Popup().setHTML(marker.infoWindow);

    new mapboxgl.Marker(element)
      .setLngLat([marker.lng, marker.lat])
      .setPopup(popup)
      .addTo(map);
  });

  fitMapToMarkers(map, markers);

  // draw route
  map.on('load', function(){
    drawRoute(start, end);
  });
};

export { initMapboxShow };

Dropzone delete picture

import Dropzone from "dropzone";
import "dropzone/dist/dropzone.css";

Dropzone.autoDiscover = false;

function initDropzones() {
  const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
  const forms = document.querySelectorAll('.dropzone');

  forms.forEach((form) => {
    const selector = "#" + form.id;
    const photosURL = form.dataset.stepPhotosUrl;

    new Dropzone(selector,
      {
        paramName: "picture",
        addRemoveLinks: true,
        init: function() {
          const thisDropzone = this;

          // Load the existing photos
          $.getJSON(photosURL).done(function (photos) {
            photos.forEach((photo) => {
              // 1. Call the default addedfile event handler
              // 2. And optionally show the thumbnail of the file:
              // 3. Make sure that there is no progress bar, etc...
              thisDropzone.emit("addedfile", photo);
              thisDropzone.emit("thumbnail", photo, photo.picture_url);
              thisDropzone.emit("complete", photo);
            });
          });

          this.on("removedfile", function(file) {
            const deletionUrl = file.deletion_url;

            fetch(deletionUrl, {
              method: "DELETE",
              headers: {
                "Accept":       "application/json",
                "Content-Type": "application/json",
                'X-CSRF-Token': csrfToken
              },
              credentials: 'same-origin'
            });
          });

        }
      }
    );
  });
}

export { initDropzones };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment