Coffeescript and Ecmascript 6 get and set keywords - coffeescript

I'm running into an issue with coffeescript where I would like to be able to use the ecmascript get and set keywords, however the syntax doesn't make sense in coffeescript.
Here's an example of the original javascript
// A Tutorial class that takes a document in its constructor
Tutorial = function (id, name, capacity, owner) {
this._id = id;
this._name = name;
this._capacity = capacity;
this._owner = owner;
};
Tutorial.prototype = {
get id() {
// readonly
return this._id;
},
get owner() {
// readonly
return this._owner;
},
get name() {
return this._name;
},
set name(value) {
this._name = value;
},
get capacity() {
return this._capacity;
},
set capacity(value) {
this._capacity = value;
}
};
And here's an example of my best guess of what that might translate into:
class Question
constructor: (id, #name, #capacity, #owner) ->
#_id = id
Question::get id() ->
return #_id
however that of course doesn't actually compile to anything useful.
I've seen a few examples of work arounds, but I guess the real question is whether there is any support for this at all in Coffescript directly?

I don't think Coffeescript does support getter/setter declaration in object literals at all. It's been discussed multiple times, see issues 64, 451, 322, 2878:
In summary: we explicitly ignore the existence of setters/getters because we consider them a bad part of JS
The best workaround you can get is
Object.defineProperty Question::, "id",
get: -> #_id
enumerable: true
configurable: true

Related

What is 'Private properties' in Dart?

While studying Dart, I noticed that private properties start with an underscore. So what do private properties mean?
class OfficialName extends Name {
// Private properties begin with an underscore
final String _title;
OfficialName(this._title, String first, String last)
: super (first, last);
#override
String toString(){
return 'S_title. ${super.toString()}';
}
}
Private properties are those properties that are only accessible in the file in which they were declared. In other words, only dart code in the dart file, where these private properties are found, "know" the private properties.
Consider the following example
In lib/foo.dart
class Foo {
var _foo = 'foo';
var bar = 'bar';
}
main() {
print(Foo()._foo); // foo
print(Foo().bar); // bar
}
Then in lib/bar.dart
import './foo.dart';
main() => {
// print(Foo()._foo); // this won't work
print(Foo().bar); // bar
}
Running both files will show the commented results. But if the print(Foo()._foo); line is uncommented in bar.dart, the compiler will throw an Error, that the getter '_foo' isn't defined for the class 'Foo'. This is because the _foo property on the Foo class is private to the foo.dart file.
In Dart, every file is a library. So it makes sense that privacy or private properties are scoped to each library.
To create a private property, be it a field or a method, simple prefix its name with an underscore _.
So when coding, if there are properties you feel that other dart files (or libraries) shouldn't access, (maybe because of isolating logic), then you can make them private (by prefixing with underscore _).
Dart privacy is indeed only on a per library basis.
I understand this way, let's talk about your example.
final String _title; means our title here is private.
If we declare a variable with underscore, we can't change its property.
Let's create an object of OfficialName and print it.
OfficialName ofName = OfficialName("Dr", "John", "kim");
print("From constructor=> title: ${ofName._title} first: ${ofName.first} last: ${ofName.last}");
Now if we like to change the attribute value of this object, we can do
ofName.first= "new value" however, we can't change _title here. I think private property as an immutable object.
Example code
class Name {
String first;
String last;
Name(this.first, this.last);
}
class OfficialName extends Name {
// Private properties begin with an underscore
final String _title;
OfficialName(this._title, String first, String last) : super(first, last);
#override
String toString() {
return 'S_title. ${super.toString()}';
}
}
// Main function
void main() {
OfficialName ofName = OfficialName("Dr", "John", "kim");
print(
"From constructor=> title: ${ofName._title} first: ${ofName.first} last: ${ofName.last}");
///let's change some property
/// this will show errors
ofName._title = "changed title";
ofName.first = "firstName";
ofName.last = "lastName";
print(
"After changed=> title: ${ofName._title} first: ${ofName.first} last: ${ofName.last}");
}
For clear information visit language-tour
The underscore determines the visibility of that identifier to the outside:
The import and library directives can help you create a modular and shareable code base. Libraries not only provide APIs, but are a unit of privacy: identifiers that start with an underscore (_) are visible only inside the library. Every Dart app is a library, even if it doesn’t use a library directive.
From the dart documentation

Avoid lazyloader attribute

I´ve been looking for how avoid return a list without the attribute lazyLoader, I want to continue using the lazyLoader but I don´t want return the attribute when I return the whole list of my entity from my controller
I´m working with .NET core.
[
{
"lazyLoader": {},
"id": "id1"
"name": "name"
},
{
"lazyLoader": {},
"id": "id2",
"name": "name2"
}
]
You can do a select of you collection only retrieving the rest of the data.
That way your objects will not have the Navigation property at all.
db.YourCollection.Where(your condition)Select(x => new { id = x.id , name = x.name } );
In Entity Framework, if you have an object where one or more of its properties use lazy loading, check its runtime type name using GetType().Name. For an object of a Car class, for example, you will notice that the runtime type is actually something called CarProxy, which is a temporary in-memory type created by Entity Framework using reflection. This "fake" proxy class's base type is Car, and has all the original Car properties, but includes an extra one called LazyLoader for properties that may need it.
If you do further checking on this "fake" CarProxy type, you will also see that Assembly.IsDynamic = true, which is indicative that the class was created dynamically using reflection (see documentation):
var TheCar = DBContext.Cars.Find(1);
Console.WriteLine(TheCar.GetType().Assembly.IsDynamic.ToString()); //will echo "true"
Luckily, Newtonsoft.Json has an override on the JsonConvert.SerializeObject() method that allows us to provide a base type, so that the resulting JSON doesn't contain properties that don't exist in that type. So, to eliminate the LazyLoader property, just provide the object's BaseType as the type parameter:
var TheCar = DBContext.Cars.Find(1);
var TheJSON = Newtonsoft.Json.JsonConvert.SerializeObject(TheCar, TheCar.GetType().BaseType);
To make sure you don't get any circular reference loops when serializing (a very high probability when using lazy loading), call the serializer with the following setting:
var TheCar = DBContext.Cars.Find(1);
var Settings = new Newtonsoft.Json.JsonSerializerSettings
{
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};
var TheJSON = Newtonsoft.Json.JsonConvert.SerializeObject(TheCar, TheCar.GetType().BaseType, Settings);
Note: This may only work on the first level deep when the serializer travels through the object. If there are yet more lazy-loading child properties of the object you provide to the serializer, the "LazyLoader" property may appear again. I haven't tested it so I can't say for sure.
I know this is old, but add
public boolean ShouldSerializeLazyLoader() { return false; }
to all the classes down the tree of the ones you want to serialize, and you will get a lazyloader free JSON.
Ref.: https://www.newtonsoft.com/json/help/html/ConditionalProperties.htm
The checked answer for this question is just working for the root object, if we have many nested lazyloaded objects, this solution will not work.
Although the answer of #Marcello-Barbiani is correct but it is not a good way to add this function to all entities we have.
The best way is create a new ContractResolver derived from DefaultContractResolver and check if property is Lazyloader then skip it as below:
public class NonLazyloaderContractResolver : DefaultContractResolver
{
public new static readonly NonLazyloaderContractResolver Instance = new NonLazyloaderContractResolver();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (property.PropertyName == "LazyLoader")
{
property.ShouldSerialize = i => false;
}
return property;
}
}
after that adding above class pass it through JsonSerializerSettings while serializing the object:
var json = JsonConvert.SerializeObject(newProduct, new JsonSerializerSettings() {
ContractResolver = new NonLazyloaderContractResolver(),
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore });
and finally if you are using asp.net core or asp.net core webapi add this contract as default contractresolver in startup.cs file:
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new NonLazyloaderContractResolver();
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});

Typescript - Get uninitialized properties after compilation

I am currently writing a wrapper around socket.io. Comming from a very object-oriented background, I want to implement the concept of Models in my framework/wrapper.
If you happen to know socket.io you might know that you get the data that is associated with an event as a parameter, now I have implemented a custom routing system where the handler of the route gets the data in an express.js like request object.
The idea is to have model classes that look something like this:
class XRequestModel
#v.String({ message: 'The username must be a string!' })
public userName: string;
}
And the route event might look something like this:
#RouteConfig({ route: '/something', model: XRequestModel })
class XEvent extends Route {
public on(req: Request<XRequestModel>, res: Response) {
// Handle Event
}
}
And to complete the example here is how the request object might look like:
class Request<T> {
public data: T;
}
Now generics in typescript are very limited since the type information is removed after compilation, I can not use the generic Request parameter ( which is the type of the model ) to get metadata from the model - Metadata, in this case, is the validation decorator. To overcome this issue I give a reference of the Model class to the RouteConfig of the RouteEvent, which is internally used and would allow me to create instances of the model, get the properties and so on...
The idea here is to give the handler of a route, a request object with pre-validated, typesafe data.
The thing holding me back from this, is the fact that unused properties, get removed after compilation by typescript, So I cannot get the metadata of the model. Initializing the class-property would solve this:
class XRequestModel
#v.String({ message: 'The username must be a string!' })
public userName: string = '';
}
But I think this makes for some very verbose syntax, and I dont want to force the user of this wrapper to init all the model properties.
An implementation side-note:
The user of the framework has to register the classes to a 'main' class and from there I can get the Route-class via decorator reflection.
When I try to get the properties of the model without initialized properties - First model example.
// Here the route.config.model refers to the model from the RouteConfig
Object.getOwnPropertyNames(new route.config.model());
>>> []
Here is what I get with initialized properties:
Object.getOwnPropertyNames(new route.config.model());
>>> [ 'userName' ]
Here a link to the GitHub repository: https://github.com/FetzenRndy/SRocket
Note that models are not implemented in this repo yet.
Basically, my question is: How can I get the properties of a class that has uninitialized properties after compilation.
The problem is that if no initialization happens, no code is emitted for the fields, so at runtime the field does not exist on the object until a value is assigned to it.
The simplest solution would be to initialize all fields even if you do so with just null :
class XRequestModel {
public userName: string = null;
public name: string = null;
}
var keys = Object.getOwnPropertyNames(new XRequestModel())
console.log(keys); // [ 'userName', 'name' ]
If this is not a workable solution for you, you can create a decorator that adds to a static field on the class and the walk up the prototype chain to get all fields:
function Prop(): PropertyDecorator {
return (target: Object, propertyKey: string): void => {
let props: string[]
if (target.hasOwnProperty("__props__")) {
props = (target as any)["__props__"];
} else {
props = (target as any)["__props__"] = [];
}
props.push(propertyKey);
};
}
class XRequestModelBase {
#Prop()
public baseName: string;
}
class XRequestModel extends XRequestModelBase {
#Prop()
public userName: string;
#Prop()
public name: string;
}
function getAllProps(cls: new (...args: any[]) => any) : string[] {
let result: string[] = [];
let prototype = cls.prototype;
while(prototype != null) {
let props: string[] = prototype["__props__"];
if(props){
result.push(...props);
}
prototype = Object.getPrototypeOf(prototype);
}
return result;
}
var keys = getAllProps(XRequestModel);
console.log(keys);

NUnit with Rhino Mocks exception: Why is it throwing this exception?

I'm getting an exception that really makes no sense to me whatsoever.
I have an Expect call for a method that takes 3 arguments into it: The types are called CallContext, IDal, and List.
NUnit throws me 2 exceptions: One for not expecting a method call that happened where the types are CallContext, System.Object, and List, and one for expecting a call that didn't happen where the types are the correct ones. The fun thing is that the only way to call the method is with the 3 types mentioned above. There is no method call with type object!
Here is the code:
private IDal mockDal;
private CallContext mockContext;
private IWorkbooksLogic mockWLogic;
private ICommercialSpaceLogic mockCLogic;
private CmWorkbook mockWorkbook;
private IList<Workbook> mockList;
private MockRepository mock;
private Random random;
[SetUp]
public void Setup() {
mock = new MockRepository();
random = new Random();
this.mockDal = mock.StrictMock<IDal>() as IDal;
this.mockContext = new CallContext();
this.mockWLogic = mock.StrictMock<IWorkbooksLogic>() as IWorkbooksLogic;
this.mockCLogic = mock.StrictMock<ICommercialSpaceLogic>() as ICommercialSpaceLogic;
this.mockWorkbook = new CmWorkbook();
this.mockList = mock.StrictMock<IList<Workbook>>() as IList<Workbook>;
}
[Test]
public void ShouldFailWhenCreateWorkbookFails() {
int randBudget = random.Next(50);
int randEntity = random.Next(50);
int randWork = random.Next(50);
WorkbookDefinitions work = new WorkbookDefinitions {
WorkbookDefinitionID = randWork
};
Budget budget = new Budget {
BudgetID = randBudget,
WorkbookDefinitions = new List<WorkbookDefinitions> { work },
};
CommercialProperty property = new CommercialProperty {
CommercialPropertyID = randEntity,
CMEntity = new CMEntity {
EntityBase = new EntityEntity { EntityCode = "random.Next(50)" }
}
};
CmWorkbook book = new CmWorkbook {
WorkbookName = String.Format("CM — {0}", property.CMEntity.EntityBase.EntityCode)
};
OperationResults results = new OperationResults();
this.mockList.Add(book);
using (mock.Record()) {
Expect.On(this.mockDal).Call(this.mockDal.GetObject<Budget, int>(randBudget)).Return(budget);
Expect.On(this.mockDal).Call(this.mockDal.GetObject<CommercialProperty, int>(randEntity)).Return(property);
Expect.On(this.mockWLogic).Call(this.mockWLogic.Create(this.mockContext, this.mockDal, this.mockList)).Return(null);
}
using (mock.Playback()) {
results = CmWorkbookLogic.CreateWorkbook(mockContext, mockDal, mockWLogic, mockCLogic, randBudget, randEntity);
}
Assert.IsFalse(results.AllSuccessful);
}
The method being called is: workbooksLogic.Create(context, dal, new List { workbook })
Here is the NUnit error:
ShouldFailWhenCreateWorkbookFails:
Rhino.Mocks.Exceptions.ExpectationViolationException : ICRUDBaseLogic`1.Create(CallContext, System.Object, System.Collections.Generic.List`1[Workbook]); Expected #0, Actual #1.
ICRUDBaseLogic`1.Create(CallContext, IDalProxy8768e63f86da4601993b4791c696ada6, System.Collections.Generic.List`1[Workbook]); Expected #1, Actual #0.
I have no idea what the heck is going on with this. Anyone have any ideas?
Rhino Mocks uses the overloaded Equals method to compare arguments of the expected invocation and the invocation that actually happened. Some of the objects you are supplying as arguments don't have Equals overloaded (i.e. List class, not sure about the others), so the only way it would work if the supplied arguments had the same references (so were the same objects) as the ones you used to set up the expectation.
You have a few options:
Use IgnoreArguments, so that arguments will not be checked at all
Provide your own constraints, so that you can check if the arguments are what you expect them to be, but without using Equals()
Make sure these are exactly the same objects (if possible)

IN with linq to object [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Shorthand conditional in C# similar to SQL 'in' keyword
I have a string variable which holds states. I want to check whether it equals to one of these three. I want it to work the way IN works in SQL Server. IS it possible to do with Linq to Objects.
i want
if(str IN ("WA","CA","CO"))
{
}
else
{
}
How to do it. I donot want to use multiple OR conditions.
unfortunately there is no IN, but you can say this
if (new[] { "WA", "CA", "CO" }.Contains(str))
{
}
It seems the wrong way around but it's the best we've got.
How about
if ((new string [] {"WA", "CA", "CO"}).Contains(str))
{
}
else
{
}
This is using the .Contains() extension method on IEnumerable<> - not full LINQ but it should work. In production code you'd want to extract the array
new string[] {"WA", "CA", "CO"}
out to a local field.
You can make an extension method:
public static class Extensions {
public static bool In<T>(this T value, params T[] options) : where T : IComparable<T> {
foreach (T option in options) {
if (value.CompareTo(option) == 0) return true;
}
return false;
}
}
Usage:
var result = someCollection.Where(x => x.Property.In(1,2,3));